很多人在使用它腾讯提供的X5服务器,来替代Android原生的WebView,如果你正是使用腾讯X5内核的话,同样NoHttp也支持Cookie同步。
步骤和上面原生WebView没区别,但是要注意几点:
- 继承不是系统的
android.webkit.WebView
,而是com.tencent.smtt.sdk.WebView
。 - 同步到X5内核时不再是
android.webkit.CookieManagerr
,而是com.tencent.smtt.sdk.CookieManager
。 - 同步到X5内核时不再是
android.webkit.CookieSyncManager
,而是com.tencent.smtt.sdk.CookieSyncManager
。
具体代码如下:
public class MyWebView extends com.tencent.smtt.sdk.WebView {
public MyWebView(Context context) {
super(context);
}
public MyWebView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
@Override
public void loadUrl(String url, Map<String, String> httpHeader) {
if (httpHeader == null) {
httpHeader = new HashMap<>();
}
// 这里你还可以添加一些自定头。
httpHeader.put("AppVersion", "1.0.0"); // 比如添加app版本信息,当然实际开发中要自动获取哦。
URI uri = null;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
e.printStackTrace();
}
if (uri != null) {
java.net.CookieStore cookieStore = NoHttp.getCookieManager().getCookieStore();
List<HttpCookie> cookies = cookieStore.get(uri);
// 同步到腾讯X5 WebView。
com.tencent.smtt.sdk.CookieManager webCookieManager = com.tencent.smtt.sdk.CookieManager.getInstance();
webCookieManager.setAcceptCookie(true);
for (HttpCookie cookie : cookies) {
String cookieUrl = cookie.getDomain();
String cookieValue = cookie.getName() + "=" + cookie.getValue()
+ "; path=" + cookie.getPath()
+ "; domain=" + cookie.getDomain();
webCookieManager.setCookie(cookieUrl, cookieValue);
}
com.tencent.smtt.sdk.CookieSyncManager.createInstance(NoHttp.getContext()).sync();
}
super.loadUrl(url, httpHeader);
}