Get cookies from a website with a path and expiration date

I currently have a webview in which you receive cookies in 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 () returns only cookie name and value pairs.

Now I would like to get more information about what cookie, for example, path and expiration ect ...

Any idea how I can extract all the "raw data" cookies?

+6
source share
2 answers

You need to redefine the loading of WebView resources in order to access the response headers (Cookies are sent as http headers). Depending on the version of Android you support, you need to override the following two methods of 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; } }); 

You can then get the contents of the URL yourself and provide it with a WebView (by creating a new WebResourceResponse) or return null and let the WebView handle it (bear in mind that this makes another call on 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; } 
+2
source

Try the following:

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

fooobar.com/questions/887005 / ...

-one
source

Source: https://habr.com/ru/post/1012916/


All Articles