How to Manage Cookies with Httpclient in Android And/Or Java

How do I manage cookies with HttpClient in Android and/or Java?

I was unable to get my own code working (I might work on it again later), but I found useful code here Android project using httpclient --> http.client (apache), post/get method and I am using the class built by Charlie Collins, which is similar to the Http Code in the ZXing Android example. I may eventually move to the ZXing code.

Android, how to get a cookie from URL via HttpClient()?

HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.178.163:8080/login/");
CookieStore cookieStore = new BasicCookieStore();
HttpContext context = new BasicHttpContext();
context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
...
HttpResponse response = client.execute(post, context);
List<Cookie> cookies = cookieStore.getCookies();
CookieMonster.eat(cookies); // :)

Android HttpClient and Cookies

I had the same problem and I used similar approach as in the question with no luck.
The thing that made it work for me was to add the domain for each copied cookie.
(BasicClientCookie cookie.setDomain(String))

My util function:

public static BasicCookieStore getCookieStore(String cookies, String domain) {
String[] cookieValues = cookies.split(";");
BasicCookieStore cs = new BasicCookieStore();

BasicClientCookie cookie;
for (int i = 0; i < cookieValues.length; i++) {
String[] split = cookieValues[i].split("=");
if (split.length == 2)
cookie = new BasicClientCookie(split[0], split[1]);
else
cookie = new BasicClientCookie(split[0], null);

cookie.setDomain(domain);
cs.addCookie(cookie);
}
return cs;
}

String cookies = CookieManager.getInstance().getCookie(url);
BasicCookieStore lCS = getCookieStore(cookies, MyApp.sDomain);

HttpContext localContext = new BasicHttpContext();
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.setCookieStore(lCS);
localContext.setAttribute(ClientContext.COOKIE_STORE, lCS);
...

How do I make an http request using cookies on Android?

It turns out that Google Android ships with Apache HttpClient 4.0, and I was able to figure out how to do it using the "Form based logon" example in the HttpClient docs:

https://github.com/apache/httpcomponents-client/blob/master/httpclient5/src/test/java/org/apache/hc/client5/http/examples/ClientFormLogin.java



import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;

/**
* A example that demonstrates how HttpClient APIs can be used to perform
* form-based logon.
*/
public class ClientFormLogin {

public static void main(String[] args) throws Exception {

DefaultHttpClient httpclient = new DefaultHttpClient();

HttpGet httpget = new HttpGet("https://portal.sun.com/portal/dt");

HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();

System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}
System.out.println("Initial set of cookies:");
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}

HttpPost httpost = new HttpPost("https://portal.sun.com/amserver/UI/Login?" +
"org=self_registered_users&" +
"goto=/portal/dt&" +
"gotoOnFail=/portal/dt?error=true");

List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("IDToken1", "username"));
nvps.add(new BasicNameValuePair("IDToken2", "password"));

httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));

response = httpclient.execute(httpost);
entity = response.getEntity();

System.out.println("Login form get: " + response.getStatusLine());
if (entity != null) {
entity.consumeContent();
}

System.out.println("Post logon cookies:");
cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}

// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}

Using Cookies across Activities when using HttpClient

(As promised a solution to this. I still don't like it and feel like I'm missing out on the "Correct" way of doing this but, it works.)

You can use the CookieManager to register your cookies (and therefore make these cookies available between apps) with the following code:

Saving cookies into the CookieManager:

List<Cookie> cookies = httpClient.getCookieStore().getCookies();

if(cookies != null)
{
for(Cookie cookie : cookies)
{
String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
CookieManager.getInstance().setCookie(cookie.getDomain(), cookieString);
}
}
CookieSyncManager.getInstance().sync();

Checking for cookies on specified domain:
if(CookieManager.getInstance().getCookie(URI_FOR_DOMAIN)

To reconstruct values for HttpClient:

DefaultHttpClient httpClient = new DefaultHttpClient(params);
String[] keyValueSets = CookieManager.getInstance().getCookie(URI_FOR_DOMAIN).split(";");
for(String cookie : keyValueSets)
{
String[] keyValue = cookie.split("=");
String key = keyValue[0];
String value = "";
if(keyValue.length>1) value = keyValue[1];
httpClient.getCookieStore().addCookie(new BasicClientCookie(key, value));
}

Best way to store & use cookies android with HTTPPost & HTTPClient?

This should help you get started:

http://docs.oracle.com/javase/tutorial/networking/cookies/definition.html

Check out this post as well:

https://stackoverflow.com/a/3587332/2495131

How can I get the cookies from HttpClient?

Please Note: The first link points to something that used to work in HttpClient V3. Find V4-related info below.

This should answer your question

http://www.java2s.com/Code/Java/Apache-Common/GetCookievalueandsetcookievalue.htm

The following is relevant for V4:

...in addition, the javadocs should contain more information on cookie handling

http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/index.html

and here is a tutorial for httpclient v4:

http://hc.apache.org/httpcomponents-client-ga/tutorial/html/index.html

And here is some pseudo-code that helps (I hope, it's based only on docs):

HttpClient httpClient = new DefaultHttpClient();
// execute get/post/put or whatever
httpClient.doGetPostPutOrWhatever();
// get cookieStore
CookieStore cookieStore = httpClient.getCookieStore();
// get Cookies
List<Cookie> cookies = cookieStore.getCookies();
// process...

Please make sure you read the javadocs for ResponseProcessCookies and AbstractHttpClient.

How can I get cookie from httpclient?

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpClientContext context = HttpClientContext.create();
BasicCookieStore cookieStore = new BasicCookieStore();
context.setCookieStore(cookieStore);

HttpGet httpget = new HttpGet("https://host/stuff");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
List<Cookie> cookies = cookieStore.getCookies();
if (cookies.isEmpty()) {
System.out.println("None");
} else {
for (int i = 0; i < cookies.size(); i++) {
System.out.println("- " + cookies.get(i).toString());
}
}
EntityUtils.consume(response.getEntity());
} finally {
response.close();
}

Please note you will need to use the official Apache HttpClient port to Android



Related Topics



Leave a reply



Submit