从webview获取包含路径和到期日期的cookie

我目前有一个webview,它在onPageFinished中获得了cookie

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的名称和值对。

现在我想获得关于该cookie的更多信息,例如路径和到期日期等…

我怎么知道如何提取cookie的所有“原始数据”?

您需要覆盖WebView的资源加载,以便访问响应标头(Cookie将作为http标头发送)。 根据您支持的Android版本,您需要覆盖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处理它(考虑到这会再次调用网络!)

 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; } 

尝试这个:

 String[] x = Pattern.compile(";").split(CookieManager.getInstance().getCookie()); 

https://stackoverflow.com/a/5840990/6371926