Question:
I do a post with android and HttpClient on one page, but I need to know a way to get cookies from this 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());
}
}
Answer:
For that you can use HttpContext
. Assign a CookieStore
to the context and pass it along with the HttpPost
in 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 on SOen . In addition to setting cookies as in the example above, you can read back cookies set by the server. To pass them back in a new request, just reuse the HttpContext
object created in new requests.