Maintain session between HttpUrlConnection Calls (Native/Webview)

User3 picture User3 · Nov 6, 2015 · Viewed 14k times · Source

Let me start with what I desire:

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

Problem - Maintain a session between native and webview parts.

My Approach to handle this:

I intend to implement a native login, in which I present the user with two EditTextboxes and a button, the user enters credentials and I post them as JSON to the server.

The Server responds with success or false. Based on Success flag I read the header values for this connection and extract the SessionCookie:

switch (responseCode) {
                case 200:

                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();

                   //IF SUCCESS

                    Map<String, List<String>> map = conn.getHeaderFields();

                    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
                        System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());
                    }

                    SSID = map.get("Set-Cookie").toString();
                    SSID = SSID.substring(1,SSID.length()-1);
                    return response.toString();
            }

and which looks like below:

Set-Cookie ,Value : [PHPSESSID=e407ef64abb71b1ea2b8e4b30db76cf0; path=/, ci_session=a%3A0%3A%7B%7D; expires=Thu, 06-Nov-2014 16:54:57 GMT; Max-Age=-31500000; path=/, ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22caedca696344458e7aa1b4ad02b3cfa0%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.130.42%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446792897%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D5f4013e4a2edd2eb891ec8a2b8e8716e; expires=Sun, 05-Nov-2017 06:54:57 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22caedca696344458e7aa1b4ad02b3cfa0%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.130.42%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446792897%3B%7Dc7eaa0945a7056db3cb9d336a02e5ecb; expires=Sun, 05-Nov-2017 06:54:57 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22caedca696344458e7aa1b4ad02b3cfa0%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.130.42%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446792897%3B%7Dc7eaa0945a7056db3cb9d336a02e5ecb; expires=Sun, 05-Nov-2017 06:54:57 GMT; Max-Age=63072000; path=/]

Caveat: In the above expires=Thu, 06-Nov-2014 16:54:57 GMT

Now I want to go to a webview and add this cookie to the header, which I am doing like:

Map<String, String> abc = new HashMap<String, String>();
            abc.put("Cookie", UniversalHttpUrlConnection.SSID);
            webView.loadUrl("https://someUrl/show_all", abc);

The above however does not work.

I tried a different approach, just to read the HTML from the above webview URL:

 public static String doHttpUrlConnectionAction(String desiredUrl, String headerValue)
            throws Exception {
        URL url = null;
        BufferedReader reader = null;
        StringBuilder stringBuilder;

        try {

            url = new URL(desiredUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Cookie", headerValue);

            connection.setRequestMethod("GET");

            connection.setDoOutput(true);


            connection.setReadTimeout(15 * 1000);
            connection.connect();


            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            stringBuilder = new StringBuilder();

            String line = null;
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            return stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {

            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ioe) {
                    ioe.printStackTrace();
                }
            }
        }

    }

The HTML I get is that of the Login page, which is essentially a redirect - as the server does not recognize the session and redirects me. What am I missing here? How can I continue the session?

Edit - further debugging:

Using a deprecated:

HttpClient httpClient = new DefaultHttpClient(); //

I get these headers:

Key : Date ,Value : Sat, 07 Nov 2015 08:22:28 GMT
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Server ,Value : Apache/2.2.26 (Unix) mod_ssl/2.2.26 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : PHPSESSID=f27454f855fc5d5b2efa478537725992; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Expires ,Value : Thu, 19 Nov 1981 08:52:00 GMT
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Cache-Control ,Value : no-store, no-cache, must-revalidate, post-check=0, pre-check=0
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Pragma ,Value : no-cache
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A0%3A%7B%7D; expires=Fri, 07-Nov-2014 18:22:28 GMT; Max-Age=-31500000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%2221d4f88af57e9c7477f48e0695bdb979%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A40%3A%22Apache-HttpClient%2FUNAVAILABLE+%28java+1.4%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884548%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D58938a4e97b08c01faa7fec0025bdc49; expires=Mon, 06-Nov-2017 08:22:28 GMT; Max-Age=63072000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%2221d4f88af57e9c7477f48e0695bdb979%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A40%3A%22Apache-HttpClient%2FUNAVAILABLE+%28java+1.4%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884548%3B%7D30e2cc6561b3fb9659c7809d0c82946d; expires=Mon, 06-Nov-2017 08:22:28 GMT; Max-Age=63072000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%2221d4f88af57e9c7477f48e0695bdb979%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A40%3A%22Apache-HttpClient%2FUNAVAILABLE+%28java+1.4%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884548%3B%7D30e2cc6561b3fb9659c7809d0c82946d; expires=Mon, 06-Nov-2017 08:22:28 GMT; Max-Age=63072000; path=/
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Vary ,Value : Accept-Encoding
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Content-Length ,Value : 95
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Connection ,Value : close
11-07 13:52:26.567 5264-5291/projects.test.com.webviewtest I/System.out: Key : Content-Type ,Value : text/html

And a warning at the start

Invalid cookie header: "Set-Cookie: ci_session=a%3A0%3A%7B%7D; expires=Fri, 07-Nov-2014 18:22:28 GMT; Max-Age=-31500000; path=/". Negative max-age attribute: -31500000

Observation Set-Cookie is coming 4 times, the first one causing an exception.

Now using a HttpUrlConnection:

HttpURLConnection conn = null;
conn = (HttpURLConnection) url.openConnection();

Following are the headers I get:

 Key : null ,Value : [HTTP/1.1 200 OK]
11-07 13:52:27.646 5264-5291/projects.test.com.webviewtest I/System.out: Key : Cache-Control ,Value : [no-store, no-cache, must-revalidate, post-check=0, pre-check=0]
11-07 13:52:27.646 5264-5291/projects.test.com.webviewtest I/System.out: Key : Connection ,Value : [close]
11-07 13:52:27.646 5264-5291/projects.test.com.webviewtest I/System.out: Key : Content-Type ,Value : [text/html]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Date ,Value : [Sat, 07 Nov 2015 08:22:29 GMT]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Expires ,Value : [Thu, 19 Nov 1981 08:52:00 GMT]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Pragma ,Value : [no-cache]
11-07 13:52:27.649 5264-5291/projects.test.com.webviewtest I/System.out: Key : Server ,Value : [Apache/2.2.26 (Unix) mod_ssl/2.2.26 OpenSSL/0.9.8e-fips-rhel5 mod_bwlimited/1.4]
11-07 13:52:27.650 5264-5291/projects.test.com.webviewtest I/System.out: Key : Set-Cookie ,Value : [PHPSESSID=9d98c8d97660664e550f19913783c089; path=/, ci_session=a%3A0%3A%7B%7D; expires=Fri, 07-Nov-2014 18:22:29 GMT; Max-Age=-31500000; path=/, ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%228cf5e634854030668573ec1f0dc9c6d9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884549%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7D9e233ffe356e965178da38e538fd8b31; expires=Mon, 06-Nov-2017 08:22:29 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%228cf5e634854030668573ec1f0dc9c6d9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884549%3B%7D53b1ee5e2e625d24d33a153a50881093; expires=Mon, 06-Nov-2017 08:22:29 GMT; Max-Age=63072000; path=/, ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%228cf5e634854030668573ec1f0dc9c6d9%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A13%3A%22182.59.216.32%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1446884549%3B%7D53b1ee5e2e625d24d33a153a50881093; expires=Mon, 06-Nov-2017 08:22:29 GMT; Max-Age=63072000; path=/]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : Vary ,Value : [Accept-Encoding]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : X-Android-Received-Millis ,Value : [1446884547643]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : X-Android-Response-Source ,Value : [NETWORK 200]
11-07 13:52:27.651 5264-5291/projects.test.com.webviewtest I/System.out: Key : X-Android-Sent-Millis ,Value : [1446884547076]

Observation: Set-Cookie is packed together, four instances.

When I try this in the Advanced Rest Client manually, everything works proper. I get the desired HTML page - authenticated.

Observation: The Advanced Rest Client App gives proper results only if I am logged into the website, in the same browser. So essentially the cookies are getting overridden.

Observation

I got fed up trying to get the session cookies from the HttpUrlConnection, what I did for a change is to load a webview and login inside of it.

Second I put up a button which fires my HttpUrlConnection - and tries to access a page which requires authentication.

Inside of this HttpUrlConnection I did something like this:

 CookieManager cookieManager = CookieManager.getInstance();
            String cookie = cookieManager.getCookie(new URL("https://urlinQuestion.com").getHost());
            System.out.println("Cookie from cookie store" + cookie);
            connection.setRequestProperty("Cookie", cookie);

So I pass the cookies which I get in the webView to the HttpUrlCOnnection. It works. Now what I feel is that inorder to reverse the order of events (As I want the cookies form UrlConnection - pass them to webview) I will have to update the cookie manager. (New Voyage starts here)

For record sake I am adding two cookies below: The first one does not work, the second one I get from the webview way and works, I find no difference in semantics though:

PHPSESSID=a3d2367f8a5a3221e9bad1a91a34fd55; ci_session=a%3A4%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%221381c152699fb61d04663c9b854ecdd7%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22182.59.245.196%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1447140920%3B%7Ddd2c014724b9ca061b50774f1fea235d


PHPSESSID=348345a2bf9f9733037915fd36a4ad6c; 
ci_session=a%3A4%3A%7Bs%3A10%3A%22
session_id%22%3Bs%3A32%3A%2209304f814a6ed6ad726dabca74b94182%22%3Bs%3A10%3A%22
ip_address%22%3Bs%3A14%3A%22182.59.202.107%22%3Bs%3A10%3A%22
user_agent%22%3Bs%3A60%3A%22Dalvik%2F2.1.0+%28Linux%3B+U%3B+Android+5.1.1%3B+Nexus+5+Build%2FLMY48B%29%22%3Bs%3A13%3A%22
last_activity%22%3Bi%3A1447127988%3B%7D18055bfdb2d59618a324aff37a58871d

Using this tool to read above

Answer

Skynet picture Skynet · Nov 15, 2015

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