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