I'm using HttpUrlConnection to perform some http request and I need to keep a session alive.
I read the doc which just say to add
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
but it does not say where.
Should I add this every time I create a HttpUrlConnection and do a request? I can't find any example...
CookieHandler.setDefault() sets the system-wide cookie handler. You should call it once.
Related
I am learning to store cookies in Android and came across several ways of implementing it. One of them being the use of CookieManager and CookieStore.
As I was going through Android docs, I came across the following statement:
To establish and maintain a potentially long-lived session between
client and server, HttpURLConnection includes an extensible cookie
manager. Enable VM-wide cookie management using CookieHandler and
CookieManager:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
I don't understand the meaning of VM-wide cookie management. I know that VM means Virtual Machine.
My Interpretations:
One way I interpreted it is, creating a CookieManagerand passing it to setDefault() makes it available throughout the application. Hence, I tried the following to test it.
URL url = new URL("http://something.com");
URI uri=new URI("http://something.com");
urlConnection = (HttpURLConnection) url.openConnection();
cks=urlConnection.getHeaderField("Set-Cookie");
//cks is a String
cookieManager=new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpCookie hc=new HttpCookie("Cookie1",cks);
cookieManager.getCookieStore().add(uri,hc);
cks1=cookieManager.getCookieStore().getCookies().get(0).getValue();
//cks1 is another String
I set cks and cks1 to TextViews and it printed cookie content/value as expected. Based on my interpretation, I tried cookieManager.getCookieStore().getCookies().get(0).getValue(); in another activity but it didn't recognise the object which means it is out of scope and not accessible. Also, created a new CookieManager and tried to get the cookies but it returned null. So, I assume this interpretation of VM-wide being accessible across activities is incorrect.
Second Interpretation was Cookies will be automatically stored when CookieManager is set up. I got it from a solution to another question on SO: Cookie management with Java URLConnection
One of the statements in the solution that suggested so:
When HttpURLConnection receives a cookie from the server the
CookieManager will receive the cookie and store it. Future requests to
the same server will automatically send the previously set cookies.
I removed cookieManager.getCookieStore().add(uri,hc); to test it and discovered that cookies are not stored automatically. So, that interpretation fails too.
ANOTHER DOUBT THAT HAUNTS ME:
Most of the solutions to storing cookies for later use suggests using SharedPreferences. The thing that haunts me is all of them stores cookies in CookieManager initially and later moves it to SharedPreferences. Why not use SharedPreferences directly?
For example:
URL url = new URL("http://something.com");
urlConnection = (HttpURLConnection) url.openConnection();
cks=urlConnection.getHeaderField("Set-Cookie");
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("cookie_name", cks); // Saving cookie
editor.commit();
So what is the point of using CookieManager and then moving it to SharedPreferences?
More details on Android's cookie management framework can be found in this doc, but in short, you only need to setDefault() once. In subsequent calls you can use CookieHandler.getDefault() and you supply the cookies to the sessions as demonstrated in this answer
Using the default implementations you'll only be able to access cookies from your own application.
In simplest terms an Android VM is the layer that translates your application bytecode into machine code and it is one VM per application - so VM-Wide means Application scoped.
SharedPrefs can be used to persist cookies between sessions, although this should be rarely useful (just my opinion)
I have an app which requires to save and send cookies back to server but i don't know how to send and get cookies.
Any good soul please help.
I can even accept answers of volley library to get and post cookies.
First, create an instance of AsyncHttpClient:
AsyncHttpClient myClient = new AsyncHttpClient();
Now set this client’s cookie store to be a new instance of PersistentCookieStore, constructed with an activity or application context (usually this will suffice):
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
myClient.setCookieStore(myCookieStore);
Any cookies received from servers will now be stored in the persistent cookie store.
To add your own cookies to the store, simply construct a new cookie and call addCookie:
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
See the PersistentCookieStore Javadoc for more information.
I'm trying to send HTTP Post requests to my webservice. It seems to work, however the cookies are not enabled.
I tried to import android.webkit.CookieManager in my Application and then use this code :
CookieManager cookieManager = new CookieManager();
cookieManager.setAcceptCookie(true);
I get an error telling me that CookieManager cannot be instancied.
Is there a way to allow cookies when sending a POST request ?
Thanks for your help.
Try this for webview cookies
CookieManager.getInstance().setCookie();
http://developer.android.com/reference/android/webkit/CookieManager.html#setCookie(java.lang.String,java.lang.String,android.webkit.ValueCallback
Is there a simple way to make sure the HttpClient does not send the cookies during a request, without removing all cookies.
By doing:
httpClient.getCookieStore().clear();
cookies are not sent, which is good.
But for other requests (where I need those cookies), I don't want to fetch new cookies again.
You can try to set the Cookie header of the request manually for that particular request
request.setHeader("Cookie","");
Edited:
So if is that not working an other approach could be to try to add an empty cookie store to that HttpClient instance, so theoretically you will have an empty cookiestore
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Add the created cookieStore to the http client instance
httpClient.setCookieStore(cookieStore);
My response is based on assumption that you are using Apache HttpClient version 4.x.
By default HttpClient 4.x introduces two protocol interceptors to the protocol processing pipeline responsible for HTTP state management: RequestAddCookies and ResponseProcessCookies. What you want is to remove RequestAddCookies while leaving ResponseProcessCookies in place.
This is how this can be done with HttpClient 4.3
CloseableHttpClient httpclient = HttpClients.custom()
.disableCookieManagement()
.addInterceptorFirst(new ResponseProcessCookies())
.build();
There are other ways to achieve the same result such as using a custom protocol interceptor that removes cookie headers from all outgoing requests, but removal of RequestAddCookies is the most efficient.
How can I disable/ignore default cookie handling of httpclient. I want to do it manually. I want to set a pre-defined cookie header for all http requests.
The latest httpclient (4.5.1) has a method called "disableCookieManagement", and it appears this just disables the internal cookie management, not the ability to send or receive cookies, and is working for me-
http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/impl/client/HttpClientBuilder.html#disableCookieManagement()
Set httpclient.setCookieStore(cookieStore); before you execute your HttpClient
Force to setup the HttpContext before executing the request:
private HttpClientContext httpContext = new HttpClientContext();
httpContext.setCookieStore(new BasicCookieStore());
The setCookieStore will create an empty cookie store to replace the default cookie store of http connection.
After that we can execute the http method:
org.apache.http.client.HttpClient.execute(HttpUriRequest, HttpContext)
Also we can reuse the cookie store (hold the BasicCookieStore) to keep the connection alive.
I could not find a way to disable/ignore cookie handling by DefaultHttpClient in Andoroid(I should have explored more into Android source code but have a time limitation). But I resolved it by removing all cookies before doing httpClient.execute() like this -
((AbstractHttpClient) myDefaultHttpClient).getCookieStore().clear();
This removes all the cookies stored by the defaultHttpClient and then you can manually handle(add/delete) cookies using -
myHttpPost.setHeader("Cookie", myCookie);
Hope it helps.