Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set a cookie to a webView in Android [duplicate]

I'm getting a HttpResponse from a server when checking if a username or password is correct. When I load the url in a webview I want the webView to have the cookie (the answer I get with postData() stored in the webView. I want the webView to pickup the cookie and load the url with that cookie stored in the webview.

I'm getting the response through.

public HttpResponse postData() {     HttpClient httpclient = new DefaultHttpClient();     HttpPost httppost = new HttpPost("https://example.com/login.aspx");      try {         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);         nameValuePairs.add(new BasicNameValuePair("txtUsername", "user"));         nameValuePairs.add(new BasicNameValuePair("txtPassword", "123"));         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));          HttpResponse response = httpclient.execute(httppost);         String responseAsText = EntityUtils.toString(response.getEntity());         Log.v(TAG , "Response from req: " + responseAsText);         return responseAsText;      } catch (ClientProtocolException e) {      } catch (IOException e) {      }     return null; } 

And I loadUrl with:

webView.loadUrl("http://a_page.com/getpage.aspx?p=home"); 

I guess I'm not really managing a cookie and I have no idea how to do so. Any suggestions or solutions?

like image 243
Joakim Engstrom Avatar asked Apr 19 '11 13:04

Joakim Engstrom


People also ask

How do I add cookies to WebView?

It's quite simple really. String cookieString = "cookie_name=cookie_value; path=/"; CookieManager. getInstance(). setCookie(baseUrl, cookieString);

Does WebView Android share cookies?

Webview properly, APP has to share cookies with Ms. Webview in the way she prefers, that is through the WebKit CookieManager.

Do WebViews share cookies?

Thankfully, UWP and iOS share their cookie containers automatically between the WebView and native http client, however Android does not.


1 Answers

It's quite simple really.

String cookieString = "cookie_name=cookie_value; path=/"; CookieManager.getInstance().setCookie(baseUrl, cookieString); 

where cookieString is formatted the same as a more traditional Set-Cookie HTTP header, and baseUrl is the site the cookie should belong to.

like image 62
700 Software Avatar answered Sep 21 '22 22:09

700 Software