I have en app with a webview to display an e-shop website.
For various reason the login par is made in a native form with a DefaultHttpClient and HttpPost.
When the user start by login, i have no problème to save the session cookie from the request to the webview cookie store.
My problem is when the user first navigate through the webview an login after, i cant retrive the webview cookie session from the cookiestore to put it to my DefaultHttpClient
this is my code :
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
CookieSyncManager.getInstance().sync();
cookieManager.setAcceptCookie(true);
DefaultHttpClient client = new DefaultHttpClient(clientConnectionManager, params);
String[] keyValueSets = cookieManager.getCookie(context.getString(R.string.cookie_domaine)).split(";");
for(String cookie : keyValueSets)
{
String[] keyValue = cookie.split("=");
String key = keyValue[0];
String value = "";
if(keyValue.length>1) value = keyValue[1];
BasicClientCookie2 cookieForRequest = (BasicClientCookie2) new BasicClientCookie2(key, value);
cookieForRequest.setDomain(context.getString(R.string.cookie_domaine));
cookieForRequest.setPath("/");
client.getCookieStore().addCookie(cookieForRequest);
}
In debug i see my session cookie but the getCookie method dont return it, i think it's because the cookie session domain start with a dot.
How can i maintain my webview session to a DefaultHttpClient request?
Related
I have created an Android application, in that I want to get Session from webview.
How to make it possible ?
Thanks.
I use this method for getting session cookies from a webview:
public static String getCookieFromAppCookieManager(String url) throws MalformedURLException {
CookieManager cookieManager = CookieManager.getInstance();
if (cookieManager == null)
return null;
String rawCookieHeader = null;
URL parsedURL = new URL(url);
rawCookieHeader = cookieManager.getCookie(parsedURL.getHost());
if (rawCookieHeader == null)
return null;
return rawCookieHeader;
}
There are two ways:
If a developer has made a httpclient, and makes an api auth call and store the cookie. Then you sync the httpclient's cookie with webview and maintain a session natively.
If user has used a webview to make an auth call and the cookie resides in the webview.
First one is your code and simply making a getter will return instance of DefaultHTTPClient. The instance will have access to cookies too. you can make async calls to auth api to get correct cookie in the instance. Make sure to keep HttpClient and Webview in sync.
For retrieving cookie in second method, you would use CookieManager object and the url which user is logged into and you need cookie for, example twitter.com See the second post here for implementation details.
Inside my service I run this code:
public class MainService extends Service {
....
....
CookieManager mCookieManager = CookieManager.getInstance();
CookieSyncManager mCookieSyncManager = CookieSyncManager.createInstance(mContext);
if (mCookieSyncManager != null) {
mCookieSyncManager.sync();
}
AsyncHttpClient myClient = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(mContext);
myClient.setCookieStore(myCookieStore);
myClient.setUserAgent("my service");
myClient.get("http://example.com/mypage/", new AsyncHttpResponseHandler() {
...
}
...
...
}
When I check my webserver logs, I can see cookies exists in request headers.
But these cookies are old cookies.
I also run this AndroidAsyncHttp code from an Activity. Same old cookies are sent.
But when I print out current cookies in my WebView, I see new cookies.
How can I send WebView's cookies with AndroidAsyncHttp ?
Clear cookie before set the cookie
myCookieStore.clear();
In my experience I don't need that CookieManager.
I only use this.
AsyncHttpClient myClient = new AsyncHttpClient();
PersistentCookieStore myCookieStore = new PersistentCookieStore(mContext);
// clear cookie to make the fresh cookie, to ensure the newest cookie is being send
myCookieStore.clear();
// set the new cookie
myClient.setCookieStore(myCookieStore);
myClient.get("http://example.com/mypage/", new AsyncHttpResponseHandler() {
...
}
Is it possible to use the cookies of a WebView in a HTTP Request? If yes, how can I do that?
Thanks
CookieManager is what you are looking for!
CookieSyncManager.createInstance(context)
Create the manager
CookieSyncManager.getInstance().startSync()
in Activity.onResume(), and call
CookieSyncManager.getInstance().stopSync()
in Activity.onPause().
To get instant sync instead of waiting for the timer to trigger, the host can call
CookieSyncManager.getInstance().sync()
Note that even sync() happens asynchronously, so don't do it just as your activity is shutting down.
Heres how you might go about using it:
// use cookies to remember a logged in status
CookieSyncManager.createInstance(this);
CookieSyncManager.getInstance().startSync();
WebView webview = new WebView(this);
webview.getSettings().setJavaScriptEnabled(true);
setContentView(webview);
webview.loadUrl([MY URL]);
Referenced from this question
EDIT:
If you wanted to do it with a HttpClient, you would need to create an HttpContext.
// Create a local instance of cookie store
CookieStore cookieStore = new BasicCookieStore();
// Create local HTTP context
HttpContext localContext = new BasicHttpContext();
// Bind custom cookie store to the local context
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
HttpGet httpget = new HttpGet("http://www.google.com/");
System.out.println("executing request " + httpget.getURI());
// Pass local context as a parameter
HttpResponse response = httpclient.execute(httpget, localContext);
Referenced from this question
I know this question has been asked a hundred times, and I've read and tried for 2 hours now, but I can't find my error :-(
I am trying to create a simple webbrowser and therefore have a webview, where I login on a site and get access to a picture area. With help of a DefaultHttpClient, I want to make it possible to download pictures in the secured area.
Therefore I am trying to share the cookies from the webview and pass them on to the HttpClient, so that it is authenticated and able to download. But whatever I try and do, I always get a 403 response back...
Basically the steps are the following:
1) Enter URL, webview loads website
2) Enter login details in a form
3) Navigate to picture and long hold for context menu
4) Retrieve the image URL and pass it on to AsynTask for downloading
Here's the code of the AsyncTask with the Cookie stuff:
protected String doInBackground(String... params) {
//params[0] is the URL of the image
try
{
CookieManager cookieManager = CookieManager.getInstance();
String c = cookieManager.getCookie(new URL(params[0]).getHost());
BasicCookieStore cookieStore = new BasicCookieStore();
BasicHttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
String[] cookieParts = null;
String cookies[] = null;
cookies = c.split(";");
for(int i=0;i<cookies.length;i++)
{
cookieParts = cookies[i].split("=");
BasicClientCookie sessionCookie = new BasicClientCookie(cookieParts[0].trim(), cookieParts[1].trim());
sessionCookie.setDomain(new URL(params[0]).getHost());
cookieStore.addCookie(sessionCookie);
}
DefaultHttpClient httpClient = new DefaultHttpClient();
httpClient.setCookieStore(cookieStore);
HttpGet pageGet = new HttpGet(new URL(params[0]).toURI());
HttpResponse response = httpClient.execute(pageGet, localContext);
if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
--> NEVER Happens, always get 403
.) One of the problems is that the webview saves some cookies for the host *www.*example.com, but the image-URL to download (params[0]) is *static.*example.com. The line
cookieManager.getCookie(new URL(params[0]).getHost());
returns null, because there is no cookie for static.example.com, but only for www.example.com.
.) When I manually say cookieManager.getCookie("www.example.com"); I get some cookies back, which I add to the HttpClient cookie store:
There are 5 cookies added
- testcookie = 0
- PHPSESSID = 320947238someGibberishSessionId
- email = my#email.net
- pass = 32423te32someEncodedPassGibberish
- user = 345542
So although these cookies, a session ID and other stuff, get added to the HttpClient, it never get's through to download an image. Im totally lost... though I guess that it either has something to do with the cookies domains, or that Im still missing other cookies.
But from where the heck should I know which cookies exist in the webview, when I have to specify a specific URL to get a cookie back?? :-(
Any advice?
I guess we have made it too complicated in above snippet.
Use these easy steps -
1)Retrieve the cookie from webView -wherever your webview is, use this code to re
String cookie = CookieManager.getInstance().getCookie(
url.toString());
Log.d("mytcs", "cookie downloadlistner " + cookie);
2) Pass this in your downloading asyncTask using params -
downloadImageTask = new DownloadImage();
downloadPDFTask.execute(url, cookie);
(I assume you know to retrieve this cookie in asyncTask, you will use params[1],
3) set this cookie in your http request using -
if (cookie != null)
con.setRequestProperty("cookie", cookie);
where con is HttpURLConnection con;
so you can set it to your need, in HttpGet.
You probably figured out the answer already coz it is a pretty late answer. But, just in case...
Try this. When you retrieve the cookie from WebView just use example.com in the domain name. When you set the cookie in BasicClientCookie and set the domain, set the domain name to .example.com. Note the "." in the beginning. Now, i think the session should work across all subdomains in your application.
I want to logout my twitter account by deleting the cookies created by it. I am able to retrive the cookies created by twitter using code:
String twit_cookie = getCookie ("http://www.twitter.com");
But how can i delete only cookies created by twitter because removeAllCookie() deletes all the cookies created by browser. How can i delete the specific cookie by URL or by name???
Please help...
CookieManager class has a method setCookie. Have you tried it like:
setCookie("http://www.twitter.com", null);
Or perhaps
setCookie("http://www.twitter.com", "auth_token=''");
You can use the method CookieManager#setCookie(String url, String value). As stated in the docs:
Sets a cookie for the given URL. Any existing cookie with the same host, path and name will be replaced with the new cookie.
The "clearest" way is to set all cookies created by twitter to expired (a time in the past). The code from this answer is almost right, except the date is in the future.
Modified code:
final String domain = "http://www.twitter.com";
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
String cookiestring = cookieManager.getCookie(domain); //get all cookies
String[] cookies = cookiestring.split(";");
for (int i=0; i<cookies.length; i++) {
String[] cookieparts = cookies[i].split("="); //split cookie into name and value etc.
// set cookie to an expired date
cookieManager.setCookie(domain, cookieparts[0].trim()+"=; Expires=Wed, 31 Dec 2000 23:59:59 GMT");
}
CookieSyncManager.getInstance().sync(); //sync the new cookies just to be sure