Pass cookies from HttpURLConnection (java.net.CookieManager) to WebView (android.webkit.CookieManager)

后端 未结 4 1971
粉色の甜心
粉色の甜心 2020-11-28 20:04

I\'ve seen answers about how this should work with the old DefaultHttpClient but there\'s not a good example for HttpURLConnection

4条回答
  •  囚心锁ツ
    2020-11-28 20:45

    As compared with DefaultHttpClient, there are a few extra steps. The key difference is how to access the existing cookies in HTTPURLConnection:

    1. Call CookieHandler.getDefault() and cast the result to java.net.CookieManager.
    2. With the cookie manager, call getCookieStore() to access the cookie store.
    3. With the cookie store, call get() to access the list of cookies for the given URI.

    Here's a complete example:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Get cookie manager for WebView
        // This must occur before setContentView() instantiates your WebView
        android.webkit.CookieSyncManager webCookieSync =
            CookieSyncManager.createInstance(this);
        android.webkit.CookieManager webCookieManager =
            CookieManager.getInstance();
        webCookieManager.setAcceptCookie(true);
    
        // Get cookie manager for HttpURLConnection
        java.net.CookieStore rawCookieStore = ((java.net.CookieManager)
            CookieHandler.getDefault()).getCookieStore();
    
        // Construct URI
        java.net.URI baseUri = null;
        try {
            baseUri = new URI("http://www.example.com");
        } catch (URISyntaxException e) {
            // Handle invalid URI
            ...
        }
    
        // Copy cookies from HttpURLConnection to WebView
        List cookies = rawCookieStore.get(baseUri);
        String url = baseUri.toString();
        for (HttpCookie cookie : cookies) {
            String setCookie = new StringBuilder(cookie.toString())
                .append("; domain=").append(cookie.getDomain())
                .append("; path=").append(cookie.getPath())
                .toString();
            webCookieManager.setCookie(url, setCookie);
        }
    
        // Continue with onCreate
        ...
    }
    

提交回复
热议问题