Skip to content Skip to sidebar Skip to footer

Get Cookies From Webview With Path And Expiration Date

I currently have a webview which get cookies in the onPageFinished mWebview = (WebView) this.findViewById(R.id.myWebView); mWebview.setWebViewClient(new WebViewClient() {

Solution 1:

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(newWebViewClient() {

            @OverridepublicWebResourceResponseshouldInterceptRequest(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")) {
                        returnexecuteRequest(request.getUrl().toString());
                    }
                }
                returnnull;
            }

            @OverridepublicWebResourceResponseshouldInterceptRequest(WebView view, String url) {
                if (url != null) {
                    returnexecuteRequest(url);
                }
                returnnull;
            }
        });

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!)

privateWebResourceResponseexecuteRequest(String url) {
        try {
            URLConnection connection = newURL(url).openConnection();
            String cookie  = connection.getHeaderField("Set-Cookie");
            if(cookie != null) {
                Log.d("Cookie", cookie);
            }
            returnnull;
            //return new WebResourceResponse(connection.getContentType(), connection.getHeaderField("encoding"), connection.getInputStream());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        returnnull;
    }

Post a Comment for "Get Cookies From Webview With Path And Expiration Date"