Maintain session between HttpUrlConnection Calls (Native/Webview)

15,485

Solution 1

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

Solution 2

It is Cookie header you are suppose to send on the request, not Set-Cookie.
Please read https://www.rfc-editor.org/rfc/rfc6265 for examples.

When your client receives session cookie in HTTP response header as

Set-Cookie: PHPSESSID=e407ef64abb71b1ea2b8e4b30db76cf0; path=/

It should add this cookie to subsequent HTTP requests header as

Cookie: PHPSESSID=e407ef64abb71b1ea2b8e4b30db76cf0

EDIT:

The native PHPSESSID is a bit confusing, but it should be ok to use the last value of ci_session cookie, e.g. from the response

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=/]

add to the folowing header to the webview request:

abc.put("Cookie", "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");

I would recommend to iterate over SSID = map.get("Set-Cookie"), test each individual 'Set-Cookie' header with something like /(ci_session=.*?);/ regex, and return the last match.

Please note, that User-Agent header from your webview should match user_agent in the session. In the cookie above it is Apache-HttpClient/UNAVAILABLE (java 1.4), and it seems that webview uses Dalvik/2.1.0 (Linux; U; Android 5.1.1; Nexus 5 Build/LMY48B).

Solution 3

A brilliant implementation of the java.net.CookieManager.

I've implemented my own idea. It's actually pretty cool. I've created my own implementation of java.net.CookieManager which forwards all requests to the WebViews' webkit android.webkit.CookieManager. This means no sync is required and HttpURLConnection uses the same cookie storage as the WebViews.



Class WebkitCookieManagerProxy:

import java.io.IOException;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.URI;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class WebkitCookieManagerProxy extends CookieManager 
{
    private android.webkit.CookieManager webkitCookieManager;

    public WebkitCookieManagerProxy()
    {
        this(null, null);
    }

    public WebkitCookieManagerProxy(CookieStore store, CookiePolicy cookiePolicy)
    {
        super(null, cookiePolicy);

        this.webkitCookieManager = android.webkit.CookieManager.getInstance();
    }

    @Override
    public void put(URI uri, Map<String, List<String>> responseHeaders) throws IOException 
    {
        // make sure our args are valid
        if ((uri == null) || (responseHeaders == null)) return;

        // save our url once
        String url = uri.toString();

        // go over the headers
        for (String headerKey : responseHeaders.keySet()) 
        {
            // ignore headers which aren't cookie related
            if ((headerKey == null) || !(headerKey.equalsIgnoreCase("Set-Cookie2") || headerKey.equalsIgnoreCase("Set-Cookie"))) continue;

            // process each of the headers
            for (String headerValue : responseHeaders.get(headerKey))
            {
                this.webkitCookieManager.setCookie(url, headerValue);
            }
        }
    }

    @Override
    public Map<String, List<String>> get(URI uri, Map<String, List<String>> requestHeaders) throws IOException 
    {
        // make sure our args are valid
        if ((uri == null) || (requestHeaders == null)) throw new IllegalArgumentException("Argument is null");

        // save our url once
        String url = uri.toString();

        // prepare our response
        Map<String, List<String>> res = new java.util.HashMap<String, List<String>>();

        // get the cookie
        String cookie = this.webkitCookieManager.getCookie(url);

        // return it
        if (cookie != null) res.put("Cookie", Arrays.asList(cookie));
        return res;
    }

    @Override
    public CookieStore getCookieStore() 
    {
        // we don't want anyone to work with this cookie store directly
        throw new UnsupportedOperationException();
    }
}

And use it by doing this on your application initialization:

android.webkit.CookieSyncManager.createInstance(appContext);
// unrelated, just make sure cookies are generally allowed
android.webkit.CookieManager.getInstance().setAcceptCookie(true);

// magic starts here
WebkitCookieManagerProxy coreCookieManager = new WebkitCookieManagerProxy(null, java.net.CookiePolicy.ACCEPT_ALL);
java.net.CookieHandler.setDefault(coreCookieManager);

Ref: Talkol - WebkitCookieManagerProxy

Share:
15,485

Related videos on Youtube

User3
Author by

User3

Learning :)

Updated on September 16, 2022

Comments

  • User3
    User3 over 1 year

    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

  • User3
    User3 over 8 years
    I agree, I am not using the String "Set-Cookie" but instead "Cookie" however the difference is that I am resending the entire string. Let me try this with what you state.
  • User3
    User3 over 8 years
    Not working, I also tried it this way: for (String cookie : cookies) { connection.setRequestProperty("Cookie", cookie.split(";", 2)[0]); System.out.println("Cookie" + cookie.split(";", 2)[0]); } Which again is not working!
  • Alex Blex
    Alex Blex over 8 years
    Ah, yes. I misread the logs. When you receive multiple Set-Cokie: name1=value1; path=..; domain=..., Set-Cokie: name2=value2; path=..; domain=..., you add them to the request as a single header Cookie: name1=value1; name2=value2.
  • Alex Blex
    Alex Blex over 8 years
    @User3 I have read the question a bit more attentively, and updated my answer. Unfortunately no good news unless you control both serverside apps.
  • User3
    User3 over 8 years
    This does not work, I have read this answer and only then posted a new question.
  • User3
    User3 over 8 years
    Not the case, I have turned off the USer agent on the server side.
  • Seb B.
    Seb B. over 8 years
    Well, what exactly does'nt work? Callbacks not called? Webview not loaded? Session not shared? Missing content? I see you're using you're on Android 5.1.1, and the Webview behaviour with cookies changed a lot. Which API-level as minimum and target? mixed-content/cookies
  • User3
    User3 over 8 years
    The session is not maintained. Period! Lets consider 5.1.1 as the Min and Max both! To add more detail, I am setting cookies in teh cookie store properly, also getting them back in the next URlConnection. But somehow the session fails. I get the login HTML in the next URL Connection.
  • User3
    User3 over 8 years
    Let us not at all consider a webview here, lets consider two URL connections one used for passing User credentials - getting "Set-Cookie" value if the user authenticates. Add these Cookies in the cookieManager CookieManager.getInstance().setCookie Then initiating a new URL connection - reading cookies - CookieManager.getInstance().getCookie and fetching the raw html from here. It breaks - gets me the login page.
  • User3
    User3 over 8 years
    However, if I login using a webview and then fetch cookies for this domain, everything works fine. The native HttpUrlConnection is able to persist the session.
  • Alex Blex
    Alex Blex over 8 years
    Mystery. Since nothing helps, would you consider some low level debugging? Try something like sudo tcpdump -i eth0 -s 0 -A -l 'tcp port 80' on the serverside and check exactly which headers are being sent and returned in both requests. It will help to identify whether it is serverside problem with session management, or clientside problem with cookie management.
  • User3
    User3 over 8 years
    Yes Alex, I would love to do that as after careful checks I see no problem with the semantics of my Cookie header, it looks exactly the same as an authenticated cookie - if we consider semantics.
  • User3
    User3 over 8 years
    Yes, this is the best possible thing that I can do now. Although an alternate.
  • Vasileios Pallas
    Vasileios Pallas over 8 years
    hmm ok, take a look at this http://stackoverflow.com/a/12731212/3763848