Get cookies from an Httpclient login on android

Asked

Viewed 683 times

3

I do a post with android and Httpclient on a page, but I need to know a way to get cookies from that connection.

this is the code I use to make the post

public static void postData(Activity activity, String user, String password) {
    // Create a new HttpClient and Post Header
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost([URL]);

    try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("Email", user));
        nameValuePairs.add(new BasicNameValuePair("Senha", password));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));


        HttpResponse response = httpClient.execute(httppost);
        System.out.println("response:" + response);
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);

    } catch (ClientProtocolException e) {
        System.out.println("ClientProtocolException: " + e.getMessage());

    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());

    }
}

1 answer

1


For this you can use HttpContext. Assign a CookieStore to the context and pass along with the HttpPost in the method execute.

Example: (Complete code here)

   // Cria uma instância local do cookie store
    CookieStore cookieStore = new BasicCookieStore();

    // Cria um contexto HTTP local
    HttpContext localContext = new BasicHttpContext();
    // Junte o cookie store com o contexto
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet("http://www.google.com/"); 

    System.out.println("executing request " + httpget.getURI());

    // Passe o contexto local como parâmetro
    HttpResponse response = httpclient.execute(httpget, localContext);

Source: that answer in Soen. In addition to assigning cookies as in the example above, you can read back the cookies assigned by the server. To pass them again in a new request, just reuse the object HttpContext created in new requests.

  • That’s what I needed! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.