从Webview获取cookie的路径和到期日期 [英] Get cookies from webview with path and expiration date
问题描述
我目前有一个webview,它在onPageFinished中获取cookie
I currently have a webview which get cookies in the onPageFinished
mWebview = (WebView) this.findViewById(R.id.myWebView);
mWebview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
String cookies = CookieManager.getInstance().getCookie(url);
Log.d("Cookie", cookies);
}
});
mWebview.loadUrl("http://www.google.com");
CookieManager.getCookie()仅返回cookie的名称和值对。
CookieManager.getCookie() only returns name and value pairs of the cookie.
现在,我想获取有关该Cookie的更多信息,例如路径和到期日期等。
Now I would like to get more information about that cookie such as the path and the expiration date ect...
关于如何提取所有原始数据的任何想法
Any idea of how can I extract all the "raw data" of the cookies?
推荐答案
您需要覆盖WebView的资源负载才能访问响应头(Cookie是作为http标头发送)。
根据所支持的Android版本,您需要重写WebViewClient的以下两种方法:
You need to override the WebView's resource loading in order to have access the the response headers (the Cookies are sent as http headers). Depending on the version of Android you are supporting you need to override the following two methods of the WebViewClient:
mWebview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
if (request != null && request.getUrl() != null && request.getMethod().equalsIgnoreCase("get")) {
String scheme = request.getUrl().getScheme().trim();
if (scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https")) {
return executeRequest(request.getUrl().toString());
}
}
return null;
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (url != null) {
return executeRequest(url);
}
return null;
}
});
然后您可以自己检索url的内容并将其提供给WebView(通过创建一个新的WebResourceResponse)或返回null并让WebView处理它(考虑到这会再次调用网络!)
You can then retrieve the contents of the url yourself and give that to the WebView (by creating a new WebResourceResponse) or return null and let the WebView handle it (take into consideration that this make another call to the network!)
private WebResourceResponse executeRequest(String url) {
try {
URLConnection connection = new URL(url).openConnection();
String cookie = connection.getHeaderField("Set-Cookie");
if(cookie != null) {
Log.d("Cookie", cookie);
}
return null;
//return new WebResourceResponse(connection.getContentType(), connection.getHeaderField("encoding"), connection.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
这篇关于从Webview获取cookie的路径和到期日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!