Skip to content Skip to sidebar Skip to footer

Sharing Cookies From Webview With Basichttprequest On Android

I'm having trouble sending cookies as part of an http get. First I go to a login page within a webview which gives me a cookie. I have checked and the cookie is being stored in t

Solution 1:

Attaching cookies is finally working for me! I might not have done it the easiest way, but at least it works. My big breakthrough was downloading and attaching the android sources, so that I could step through and see what was happening. There are instructions here http://blog.michael-forster.de/2008/12/view-android-source-code-in-eclipse.html - scroll down and read the comment from Volure for the simplest download. I highly highly recommend doing this if you're developing on Android.

Now on to the working cookies code - most changes were in the code that actually gets me my webpage - I had to set up a COOKIE_STORE and a COOKIESPEC_REGISTRY. Then I also had to change my connection type because the cookies code was casting it to a ManagedClientConnection:

publicstatic HttpResponse getMeAWebpage(String host_string, int port, String url)throws Exception {
    HttpParamsparams=newBasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF-8");
    HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
    HttpProtocolParams.setUseExpectContinue(params, true);
    //params.setParameter("cookie", cookie);BasicHttpProcessorhttpproc=newBasicHttpProcessor();
    // Required protocol interceptors
    httpproc.addInterceptor(newRequestContent());
    httpproc.addInterceptor(newRequestTargetHost());
    // Recommended protocol interceptors
    httpproc.addInterceptor(newRequestConnControl());
    httpproc.addInterceptor(newRequestUserAgent());
    httpproc.addInterceptor(newRequestExpectContinue());
    httpproc.addInterceptor(newRequestAddCookies());


    HttpRequestExecutorhttpexecutor=newHttpRequestExecutor();

    HttpContextcontext=newBasicHttpContext(null);
    // HttpHost host = new HttpHost("www.svd.se", 80);HttpHosthost=newHttpHost(host_string, port);
    HttpRouteroute=newHttpRoute(host, null, false);

    // Create and initialize scheme registry SchemeRegistryschemeRegistry=newSchemeRegistry();
    schemeRegistry.register(newScheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(newScheme("https", SSLSocketFactory.getSocketFactory(), 443));

    SingleClientConnManagerconn_mgr=newSingleClientConnManager(params, schemeRegistry);
    ManagedClientConnectionconn= conn_mgr.getConnection(route, null/*state*/);
    ConnectionReuseStrategyconnStrategy=newDefaultConnectionReuseStrategy();

    context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

    CookieStorecookie_store=newBasicCookieStore();
    cookie_store.addCookie(cookie);
    context.setAttribute(ClientContext.COOKIE_STORE, cookie_store);

    // not sure if I need to add all these specs, but may as wellCookieSpecRegistrycookie_spec_registry=newCookieSpecRegistry();
    cookie_spec_registry.register(
            CookiePolicy.BEST_MATCH,
            newBestMatchSpecFactory());
    cookie_spec_registry.register(
            CookiePolicy.BROWSER_COMPATIBILITY,
            newBrowserCompatSpecFactory());
    cookie_spec_registry.register(
            CookiePolicy.NETSCAPE,
            newNetscapeDraftSpecFactory());
    cookie_spec_registry.register(
            CookiePolicy.RFC_2109,
            newRFC2109SpecFactory());
    cookie_spec_registry.register(
            CookiePolicy.RFC_2965,
            newRFC2965SpecFactory());
    //cookie_spec_registry.register(//        CookiePolicy.IGNORE_COOKIES,//        new IgnoreSpecFactory());
    context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, cookie_spec_registry);

    HttpResponseresponse=null;

    try {
        if (!conn.isOpen()) {
            conn.open(route, context, params);  
        }

        BasicHttpRequestrequest=newBasicHttpRequest("GET", url);
        System.out.println(">> Request URI: "
                + request.getRequestLine().getUri());
        System.out.println(">> Request: "
                + request.getRequestLine());

        request.setParams(params);
        httpexecutor.preProcess(request, httpproc, context);
        response = httpexecutor.execute(request, conn, context);
        response.setParams(params);
        httpexecutor.postProcess(response, httpproc, context);

        Stringret= EntityUtils.toString(response.getEntity());
        System.out.println("<< Response: " + response.getStatusLine());
        System.out.println(ret);
        System.out.println("==============");
        if (!connStrategy.keepAlive(response, context)) {
            conn.close();
        } else {
            System.out.println("Connection kept alive...");
        }
    } catch(UnknownHostException e) {
        System.out.println("UnknownHostException"); 
    } catch (HttpException e) {
        System.out.println("HttpException"); 
    } finally {
        conn.close();
    }

    return response;
}

My code to set up my cookie lives in the same class as getMeAWebpage() looks like:

publicstaticvoid SetCookie(String auth_cookie, String domain)
{
    String[] cookie_bits = auth_cookie.split("=");
    cookie = new BasicClientCookie(cookie_bits[0], cookie_bits[1]);
    cookie.setDomain(domain); // domain must not have 'http://' on the front
    cookie.setComment("put a comment here if you like describing your cookie");
    //cookie.setPath("/blah"); I don't need to set the path - I want the cookie to apply to everything in my domain//cookie.setVersion(1); I don't set the version so that I get less strict checking for cookie matches and am more likely to actually get the cookie into the header!  Might want to play with this when you've got it working...
}

I really hope this helps if you're having similar problems - I feel like I've been banging my head against a wall for a couple of weeks! Now for a well-deserved celebratory cup of tea :o)

Post a Comment for "Sharing Cookies From Webview With Basichttprequest On Android"