Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Http cookie store in Android

I am developing an Android client for the site with authorization. I have a post method. Example my code:

public void run() {
    handler.sendMessage(Message.obtain(handler, HttpConnection.DID_START));
    httpClient = new DefaultHttpClient();
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), 25000);
    HttpResponse response = null;
    try{            
        switch (method){
        case POST:
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeaders(headers);
            if (data != null) httpPost.setEntity(new StringEntity(data));
            response = httpClient.execute(httpPost);
            break;
        }
        processEntity(response);

    }catch(Exception e){
        handler.sendMessage(Message.obtain(handler, HttpConnection.DID_ERROR, e));

    }
    ConnectionManager.getInstanse().didComplete(this);      
}

How to keep cookies?

like image 950
monomi Avatar asked Jun 15 '26 14:06

monomi


1 Answers

You get your cookies from HttpResponse response:

Header[] mCookies = response.getHeaders("cookie");

and add them to your next request:

HttpClient httpClient = new DefaultHttpClient();

//parse name/value from mCookies[0]. If you have more than one cookie, a for cycle is needed.
CookieStore cookieStore = new BasicCookieStore();
Cookie cookie = new BasicClientCookie("name", "value");
cookieStore.addCookie(cookie);

HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

HttpGet httpGet = new HttpGet("http://www.domain.com/"); 

HttpResponse response = httpClient.execute(httpGet, localContext);
like image 176
Indrek Kõue Avatar answered Jun 18 '26 04:06

Indrek Kõue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!