DefaultHttpClient post get session cookie and pass to WebView android - android

I've found a few answers to this question here on SO, but I'm not having success implementing them so hoped that someone could check over my code and tell me where i'm going wrong.
I have verified that my cookie is being set from the DefaultHttpClient and am writing it out with Log.d as you can see in my code snippet below. It's all there, it's just not getting set for the WebView which is called at the bottom of this code segment. The cookie being passed down is a session cookie from my Asp.net mvc project. Any ideas why it's not keeping me logged in when the WebView hits the site? Don't let the facebook wording throw you off, that I all have working, this cookie is for my own server that is passing down a session cookie to keep me logged into my own site (based on my facebook stuff).
Cookie sessionCookie = FacebookLoginService.cookie;
Log.d("intialwebview",sessionCookie.toString());
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
String cookieString = sessionCookie.getName() + "=" + sessionCookie.getValue() + "; domain=" + sessionCookie.getDomain();
Log.d("intialwebview",cookieString);
cookieManager.setCookie(FacebookLoginService.cookie.getDomain(), cookieString);
CookieSyncManager.getInstance().sync();
}
//end cookie section
int userId = prefs.getInt(C.USER_ID, 0);
webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setUserAgentString(webView.getSettings().getUserAgentString() + "(Rambo)");
webView.getSettings().setJavaScriptEnabled(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.loadUrl(C.BaseUrl + "home/firstpage");
EDIT: I also tried creating the web view in code with:
WebView webView = new WebView(this);
same result. Cookie isn't being sent to the webview.

finally got this sorted by using an Asynctask and running a sleep in the background.

You have used this line -
if (sessionCookie != null) {
cookieManager.removeSessionCookie();
}
To ensure you receive new cookie everytime.
Seems like you have gone through same issue
as I faced, check below link -
removeSessionCookie() issue of android, (code.google.com)
it says that removeSessionCookie() is implemented in a thread, so whenever it is
called; a thread starts and after your setCookie(url, cookieString); is called,
it removes the new cookie you just set.
So for some devices it works well as removeSessionCookie() is already executed,
while, for some, it remove the cookie, and we get that problem.
I suggest you remove this removeSessionCookie(); as you are setting only one cookie, so it won't conflict with other cookies. Your code will work seamlessly.

Related

how i can load a page in android WebView with cookies?

i have cookies,want to send the cookie to WebView,how i can do?
i use JSOUP to get cookies from login page and i use the follow code but not working
webview.LoadUrl(URL, Cookies)
I had to do something like this a couple of weeks ago. I ditched the webview though and used a recyclerview for the info because of data and ram consumption.
res = Jsoup.connect(url)
.data("user", user, "passwrd", pass)
.method(Connection.Method.POST)
.execute();
String sessionId = res.cookie("PHPSESSID");
The code up there is actually from Jsoup's creator himself on how to store cookies. Then its a matter of setting the cookiemanager to these cookies.
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.setCookie(url,String.format("%s=%s",
"PHPSESSID", sessionId));
Then I just loaded the webview. I think a really important line here is formatting the string in the second parameter of the setCookie() method to match how the cookie is actually a Map with a key and value of PHPSESSID and the cookies characters. PHPSESSID is the id name that shows up for me in the cookie.

Perform HTTP requests using cookies from webview

I have this scenario which my app shows in a webView a 2-page login process.
The first page asks only to which domain to you plan on connecting.
The second page asks for the credentials.
I'm trying to perform the login in the webView and then execute requests from my native code.
I realize I need to get the stored cookie from the webView (but from which url? from the first page or the second one?), and then use the cookie for the native code requests.
Can someone please tell me how to go about it? The login process is easy - the user logs in through the webview - fine. Now, I know how to use the cookie manage but I dont know which cookie am I suppose to look for - is it the url of the first login page? is it the second one? does it matter?
Next, how do I use the cookie to send back to server with a GET request so the server will know I'm authenticated?
I appreciate the answers I'm clueless and begging for help :)
Since the accepted answer does not really describe how it is done:
Put these lines somewhere where your app starts:
CookieHandler.setDefault(new CookieManager()); // Apparently for some folks this line works already, for me on Android 17 it does not.
CookieSyncManager.createInstance(yourContext); // or app will crash when requesting cookie
And then in your connection:
String cookies = CookieManager.getInstance().getCookie(urlString);
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
// conn.setRequestMethod("GET");
// conn.setDoInput(true);
if (cookies != null)
conn.setRequestProperty("Cookie", cookies);
// Starts the query
conn.connect();
I have done the opposite of you: I log in with loopj Android Asynchronous Http Client, and want the session cookies to apply to a webview, for the same website. I don't know if it will help you, but, I am going to post my code for copying over the cookies. Maybe seeing the process will help you to look for the items you need... to copy cookies from webview, to HTTP. I can't offer further help, since I'm fairly new at Android. (And, of course, I adapted my code from other people's posts.)
Class variable declarations:
private AsyncHttpClient loopjClient = new AsyncHttpClient();
private PersistentCookieStore myCookieStore;
onCreate() initialization:
myCookieStore = new PersistentCookieStore(this);
loopjClient.setCookieStore(myCookieStore);
After HTTP login:
// get cookies from the generic http session, and copy them to the webview
CookieSyncManager.createInstance(getActivity().getApplicationContext());
CookieManager.getInstance().removeAllCookie();
CookieManager cookieManager = CookieManager.getInstance();
List<Cookie> cookies = myCookieStore.getCookies();
for (Cookie eachCookie : cookies) {
String cookieString = eachCookie.getName() + "=" + eachCookie.getValue();
cookieManager.setCookie("http://www.example.com", cookieString);
//System.err.println(">>>>> " + "cookie: " + cookieString);
}
CookieSyncManager.getInstance().sync();
// holy ****, it worked; I am automatically logged in for the webview session
Note that loopj is like the webview, in that all cookie management and sending are automatic. I just copy all cookies for the domain. I think you'd be fine, doing the same... thus, no worry about whether from the first or second page.
At the end I found my way and it was pretty simple.
Once the user logs in through the webview - a cookie is set on the device.
Later on once I want to perform Native api calls on the service I ask the cookie manager for the cookie that was set based on the url.
I then take the important header that is used to authenticate on the server and send it along with my api calls.

Jsoup cookie authentication from cookiesyncmanager to scrape from https site

I have an android application using a webview on which the user has to log in with username and password before being redirected to the page i would like to scrape data off with jsoup. Since the jsoup thread would be a different session the user would have to login again.
Now i would like to use the cookie received from the webview to send with the jsoup request to be able to scrape my data.
The cookie is being synced with cookiesyncmanager with following code. This is basically where I am stuck cause i dont know how to read out the cookie nor how to attach it to the jsoup request. Please help? :)
public void onPageFinished(WebView view, String url) {
CookieSyncManager.getInstance().sync();
The jsoup scrape I am doing after the user has logged in with something like this:
doc = Jsoup.connect("https://need.authentication.com").get();
Elements elements = doc.select("span.tabCount");
Element count = elements.first();
Log.d(TAG, "test"+(count));
I'm not an android developer but maybe you can try something like this:
final String url = "https://need.authentication.com";
// -- Android Cookie part here --
CookieSyncManager.getInstance().sync();
CookieManager cm = CookieManager.getInstance();
String cookie = cm.getCookie(url); // returns cookie for url
// ...
// -- JSoup part here --
// Jsoup uses cookies as "name/value pairs"
doc = Jsoup.connect("https://need.authentication.com").header("Cookie", cookie).get();
// ...
I hope this helps a bit, but as i said before: im no android developer (and code isn't tested!)
Here's some documentation:
CookieManager
CookieSyncManager
Jsoup Connection

How to sync cookies with android webview?

I have been creating an app which consist of a lo-gin page for a site. I am using HttpGet method and DefaultHttpClient for making connection. Everything works fine in with this. I will be receiving json response once the lo-gin is successful , in which i will be getting an URL to load with web-view. While loading the URL in web-view the cookies is not getting sync.I have been breaking my head for past one week. Can any one help me to solve this problem.Thanks in advance.
Finally after spending a 10 days i found a solution.
if (!Utils.cookies.isEmpty()){
CookieSyncManager.createInstance(WebViewActivity.this);
CookieManager cookieManager = CookieManager.getInstance();
for (Cookie cookie : Utils.cookies) {
Cookie sessionInfo = cookie;
String cookieString = sessionInfo.getName() + "=" + sessionInfo.getValue() + "; domain=" + sessionInfo.getDomain();
cookieManager.setCookie(sessionInfo.getDomain(), cookieString);
CookieSyncManager.getInstance().sync();
}
}
this piece of code worked for me.
For newer APIs , i.e API 21(Lollipop) and above, CookieSyncManager has been deprecated and CookieSyncManager.getInstance().sync(); can be replaced by CookieManager.getInstance().flush(); to write cookies to a persistent storage.

setting Cookies in WebView android

I'm trying to set some cookies on my WebView to open a browser with the same session that I have on my app.
I read a lot of answers but they don't work for me. The only solution I've found is in the loadUrl, hardcode the cookie data in extraHeaders, but as expected this only works for this requests, and doesn't maintain the session.
The code that I have is:
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieManager.removeSessionCookie();
cookieManager.setCookie("http://xx.xxx.example.com","mid="+MySession.GetSession().sessionId+" ; Domain=.example.com");
cookieSyncManager.sync();
String cookie = cookieManager.getCookie("http://xx.xxx.example.com");
Log.d(LOGTAG, "cookie ------>"+cookie);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new TuWebViewClient());
mWebView.loadUrl("http://xx.xx.example.com");
getCookie() returns the correct data, but when I read the cookies from the server, those are empty. What is wrong? Please advise.
Thank you!!!
Solved!!!! the problem is with the webView, I dont know what happend, but If I create the
WebView webView = new WebView(Activity.this);
it works. If I read the webview from activity with findViewById() it doesn't work.
Also if you need to set a list of cookies that you received previously from a website.
All you have to do is use a for-loop to go through and set all of them . It helped me to solve the situation
CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mWebView.getContext());
...
cookieSyncManager.sync();
is the cause of problem. You should do like this:
CookieSyncManager.createInstance(mWebView.getContext());
...
CookieSyncManager.getInstance().sync();
And there will be no need to manually create WebView...

Categories

Resources