Get cookies from a session started with HTTPClient on android

3

I do a post with android and HttpClient on a page, but I need to know a way to get the 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());

    }
}
    
asked by anonymous 08.04.2014 / 22:28

1 answer

1

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

Example: (Full 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: this 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 back on a new request, just reuse the HttpContext object created on new requests.

    
09.04.2014 / 06:44