Get cookies from webview with path and expiration date

后端 未结 1 686
再見小時候
再見小時候 2021-01-02 02:43

I currently have a webview which get cookies in the onPageFinished

mWebview = (WebView) this.findViewById(R.id.myWebView);

    mWebview.setWebViewClient(new          


        
相关标签:
1条回答
  • 2021-01-02 03:27

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

    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;
        }
    
    0 讨论(0)
提交回复
热议问题