Maintain session between HttpUrlConnection Calls (Native/Webview)

后端 未结 4 1870
长情又很酷
长情又很酷 2021-02-12 21:01

Let me start with what I desire:

I want to make an app which is part native and part webviews.

Problem - Maintai

4条回答
  •  迷失自我
    2021-02-12 21:55

    The closest I could get to this is, by using a webview as login. Then you can continue your session in the HttpUrlConnection, with the cookies fetched from webview. The cookies can be used as follows:

    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
    
        // Fetch and set cookies in requests
        CookieManager cookieManager = CookieManager.getInstance();
        String cookie = cookieManager.getCookie(urlConnection.getURL().toString());
        if (cookie != null) {
            urlConnection.setRequestProperty("Cookie", cookie);
        }
        urlConnection.connect();
    
        // Get cookies from responses and save into the cookie manager
        List cookieList = urlConnection.getHeaderFields().get("Set-Cookie");
        if (cookieList != null) {
            for (String cookieTemp : cookieList) {
                cookieManager.setCookie(urlConnection.getURL().toString(), cookieTemp);
            }
        }
    
        InputStream in = new BufferedInputStream (urlConnection.getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    

提交回复
热议问题