Android: Share Session Between Webview and Httpclient

Sharing session between httpClient and webView issue in android 4.4+

I have solved my problem. OnPageStarted event of web view was getting called twice in which i was retrieving cookies,refer this link.With simple counter ,i restricted the retrieval of cookie only on first occasion and now its working fine

Shared Cookies between WebView and HTTPClient?

Here is my code snippet that finally worked (its pseudo code as in parts of it were ripped out of my project and some things like calling MyApplication via a Singleton were more to illustrate what to do rather than how it should be done with best practices):

http://gist.github.com/610754

Http session synchronization between webview and java http client in Android

I have solved this issue:

public void syncSession(final Context ctx){

new Thread(new Runnable(){
public void run(){

//Products will be stated in memory
ProductManager pm = ProductManager.getInstance();

// HttpClient httpclient = new DefaultHttpClient();
HttpPost httpget = new HttpPost(UrlConstants.SERVICE_URL_SYNC);
HttpResponse response;
String result = null;
try {
response = httpclient.execute(httpget);
//write db to

} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

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

if (! cookies.isEmpty()){

CookieSyncManager.createInstance(ctx);
CookieManager cookieManager = CookieManager.getInstance();

//sync all the cookies in the httpclient with the webview by generating cookie string
for (Cookie cookie : cookies){

Cookie sessionInfo = cookie;

String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
cookieManager.setCookie(UrlConstants.SERVICE_PRE_URL, cookieString);
CookieSyncManager.getInstance().sync();
}
}

}
}).start();
}

Android sync cookies webview and httpclient

In your code, you seem to be doing opposite of what you wish to do (Get cookie from Webview and set in HttpClient)

Edit: From Mor Haviv's answer -

You need to Define a global variable that stores current url in the view -

private static String getUrl;

Getting cookie from webview -

@Override
public void onPageFinished(WebView view, String url){
getUrl = view.getUrl();
String cookies = CookieManager.getInstance().getCookie(getUrl);
Log.d(TAG, "All the cookies in a string:" + cookies);
}

Reference for above code

Set this string named 'cookies' in your HttpClient -

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;

}
//And, use the same 'getUrl' here to fetch the cookie. (Haviv's addition)
String cookies = CookieManager.getInstance().getCookie(getUrl);
BasicCookieStore lCS = getCookieStore(cookies, YOUR_APP_DOMAIN);

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

PS - Put your app's domain at 'YOUR_APP_DOMAIN'
And, I couldn't check the code as I don't have your domain.

Reference for above code

Android: Using Http Client and Webview to automate logging in (wordpress site)

Hopefully this can help someone, I found a nice, simple solution to this problem.

Although I had tried and discredited the javascript route, I gave it another go and it worked perfectly.

What I did differently is override the onPageLoaded function like I learned to do in the above, failing way^ and did the javascript work inside of it. I also have a static variable (loadCount I believe) that ensures that it logs in only once per instance, so as to not drag down page load times.

I had troubles with it before, I believe, because it wasn't waiting for the page to load and the javascript was searching for elements that hadn't loaded yet(maybe?).

So here is the working code:

    myWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {

loadCount = 0;
if (loadCount == 0) {
myWebView.loadUrl(
"javascript:document.getElementById('user_login').value = '" + prfs.getString("Username", "Incorrect credentials") + "';" +
"javascript:document.getElementById('user_pass').value = '" + prfs.getString("Password", "Incorrect credentials") + "';" +
"javascript:document.getElementById('wp-submit').click();"

);
loadCount++;
} else if (loadCount == 1) {
myWebView.loadUrl(url);

}
}
});


Related Topics



Leave a reply



Submit