setcookie in cookiemanager not working on Android - java

I'm using cookiemanager in androidapp.
I called an instance of cookiemanager and tried to set cookies using cookiemanager.setcookie(url,string).
But my cookiemanager instance doesnot set any cookies. I tried checking every answer on SO, couldn't solve the problem. Anyone with ideas would be greatly helpful.
public void syncCookieStoreToWebView() {
PersistentCookieStore myCookieStore = ReferenceHolder.getCookieStore();
List<Cookie> cookies = myCookieStore.getCookies();
final CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(getActivity());
CookieSyncManager.getInstance().startSync();
final CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if (! cookies.isEmpty()){
//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(ReferenceHolder.BASE_URL, cookieString);
cookieSyncManager.sync();
}
cookieSyncManager.sync();
System.out.println("COOKIEMAN" + cookieManager.getCookie(ReferenceHolder.BASE_URL));
}
}

The cookie can't include the semicolon, because the semicolon means separator in the cookie string. If you want this, please encode firstly.

David Wasser and AnswerZhao's answer is right, and for my experience, you can just set each key=value use setCookie like this:
for (Cookie cookie : cookies){
Cookie sessionInfo = cookie;
// set first key=value
String cookieStr = sessionInfo.getName() + "=" + sessionInfo.getValue();
cookieManager.setCookie(ReferenceHolder.BASE_URL, cookieStr);
// set second key=value
cookieStr = "domain=" + sessionInfo.getDomain();
cookieManager.setCookie(ReferenceHolder.BASE_URL, cookieStr);
// set ... key=value
cookieSyncManager.sync();
}

Related

How to clear HttpAuthRequest credentials

I'm doing an app that logs users into websites that have an authentication popup using webView.
The problem comes when logging in and then going back to log in with different credentials, causing to skip HttpAuthRequest and therefore being logged in with the first credentials
What should I do?
The below lines of code is enough for clearing the cookies of Web View
CookieSyncManager.createInstance(context);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
CookieSyncManager.getInstance().sync();
Happy Coding! Thanks.
I did the trick logging in like this:
// Prefix http:// or https://
String prefix = url.substring(0, url.indexOf("/") + 2);
// Prefix + username +: + password + # + url without prefix
String finalUrl = prefix + username + ":" + password + "#" + url.substring(url.indexOf("/") + 2);
webView.loadUrl( finalUrl );
Instead of using onReceivedHttpAuthRequest

How to get session token form url?

Lets say..
if i hit google with https://www.google.com it will create a session, for the responce it
will create url with session tokn like..
https://www.google.co.in/?gfe_rd=cr&ei=oFBjVJSvLqnM8gft5YDwAQ&gws_rd=ssl.
My question is
am connecting to google with the code:
URL url = new URL(test);
URLConnection conn = url.openConnection();
this will connect to google.
for this google creates a session.
then how would i get a session token back to my code?
You can get the session token from the cookie of the browser. You can, find the cookie settings->advanced settings->privacy->content settings->allcookie and site data then search www.google.com and select sid and copy the content .
You can extract any cookie, not only the one containing the session with the following approach:
Since a server may set multiple cookies in a single request, we will need to loop through the response headers, looking for all headers named "Set-Cookie".
String headerName=null;
for (int i=1; (headerName = uc.getHeaderFieldKey(i))!=null; i++) {
if (headerName.equals("Set-Cookie")) {
String cookie = urlConn.getHeaderField(i);
The string returned by the getHeaderField(int index) method is a series of name=value separated by semi-colons (;). The first name/value pairing is actual data string we are interested in (i.e. "sessionId=0949eeee22222rtg"), the subsequent name/value pairings are meta-information that we would use to manage the storage of the cookie (when it expires, etc.).
cookie = cookie.substring(0, cookie.indexOf(";"));
String cookieName = cookie.substring(0, cookie.indexOf("="));
String cookieValue = cookie.substring(cookie.indexOf("=") + 1, cookie.length());
This is basically it. We now have the cookie name (cookieName) and the cookie value (cookieValue).
the above explanation was based on example provided in http://www.hccp.org/java-net-cookie-how-to.html#retrieving_cookies
A more sophisticated approach is to use CookieAccessor class:
public void getCookieUsingCookieHandler() {
try {
// Instantiate CookieManager;
// make sure to set CookiePolicy
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
// get content from URLConnection;
// cookies are set by web site
URL url = new URL("http://host.example.com");
URLConnection connection = url.openConnection();
connection.getContent();
// get cookies from underlying
// CookieStore
CookieStore cookieJar = manager.getCookieStore();
List <HttpCookie> cookies =
cookieJar.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
} catch(Exception e) {
System.out.println("Unable to get cookie using CookieHandler");
e.printStackTrace();
}
}
In any approach you follow you need to know what is the name of the cookie holding the session id, so that you can get the value from it. E.g a java web application usually creates a cookie with name "JSESSIOINID"

setting cookie to null not working in java

i want to remove cookie with domain name and context path as "/" which is running in my cloud server.
i have below code for clearing cookie in cloud server
Cookie cookie = new Cookie(cookieName, null);// cookieName = TEST_COOKIE
String cookiePath = request.getContextPath();
cookie.setPath(cookiePath); // path = "/"
cookie.setDomain("mydomain.com");
cookie.setMaxAge(0);
response.addCookie(cookie);
if i notice the cookie in my browser i have below details
cookie name = "TEST_COOKIE" value = "MUZJd3NuNDhy" domain = "mydomain.com" path = "/"
where in my localhost, above code works fine, without setting domain name. even i tried with empty domain name which is not working. dont know how to proceed with this, direction is much appreciated.
EDIT -
below code without domain in localhost is working fine with context path as /MyApp.
Cookie cookie = new Cookie(cookieName, null);
String cookiePath = request.getContextPath();
cookie.setPath(cookiePath); // path = "/"
cookie.setMaxAge(0);
response.addCookie(cookie);
when i removed contextPath "/MyApp", it stopped working in localhost too, where in my cloud server my context path is "/" .
After lot of debugging, i found the request.getContextPath was returning empty string instead of "/" in my remote server, and in jave doc
* Returns the portion of the request URI that indicates the context
* of the request. The context path always comes first in a request
* URI. The path starts with a "/" character but does not end with a "/"
* character. For servlets in the default (root) context, this method
* returns "". The container does not decode this string.
since i am having root context , the method return empty string instead of "/", i have fixed it by below code and it is working now.
if (cookiePath.isEmpty()) {
cookie.setPath("/");
} else {
cookie.setPath(cookiePath);
}
You cannot set a Cookie as null but you can delete it (i.e. : when you'll try to get it next time, it will return null).
Just change your first line with :
Cookie cookie = new Cookie(cookieName, "");
String cookiePath = request.getContextPath();
cookie.setPath(cookiePath); // path = "/"
cookie.setDomain("mydomain.com");
cookie.setMaxAge(0);
response.addCookie(cookie);

Setting cookie in JSP and retrieving from non servlet class

I have a situation where i need to set cookie in JSP and i need to get those cookie in normal java class.
The JSP:
CookieManager manager = new CookieManager();
CookieHandler.setDefault(manager);
CookieStore cookieJar = manager.getCookieStore();
// create cookie
HttpCookie cookie = new HttpCookie("UserName", "John Doe");
// add cookie to CookieStore for a
// particular URL
URL url = new URL("http://localhost:8080");
url.openConnection().connect();
cookieJar.add(url.toURI(), cookie);
System.out.println("Added cookie using cookie handler");
%>
Below is the Java class [not a servlet class] and this class is running in the server and this is invoked not after the JSP call but somewhere in the application only if any event occurs. below is the code where i wrote to capture cookies.
URL url = new URL("http://localhost:8080");
URLConnection conn = url.openConnection();
conn.getContent();
CookieManager cm = new CookieManager();
CookieHandler.setDefault(cm);
cm.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieStore cs = cm.getCookieStore();
List <HttpCookie> cookies = cs.getCookies();
for (HttpCookie cookie: cookies) {
System.out.println("CookieHandler retrieved cookie: " + cookie);
}
would this scenario works if i want to retrieve the cookies in non servlet class?
The output of the above code will return empty list.
However if i write a servet class with request.getCookie("UserName") I will see the cookie value.
Here i need to understand how would i get the cookie value without using request object.
Because request object is not always passed in multiple invocation of java class. And i am not using session.
please let me know if you have any better approach.
Thanks-
Instead Use the getHeaderFields() method from the connection Object to get the full list of Name-Value pairs representing the header fields of the specific connection
Cookie information(if present)should be under the “Set-Cookie” header field.
Map<String, List<String>> headerFields = conn.getHeaderFields();
Set<String> headerFieldsSet = headerFields.keySet();
Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();
Then iterate over the Set and check if the cookie is present. If it is present print it out.
while (hearerFieldsIter.hasNext()) {
String headerFieldKey = hearerFieldsIter.next();
if ("Set-Cookie".equalsIgnoreCase(headerFieldKey)) {
List<String> headerFieldValue = headerFields.get(headerFieldKey);
for (String headerValue : headerFieldValue) {
System.out.println("Cookie Found...");
String[] fields = headerValue.split(";\s*");
String cookieValue = fields[0];
System.out.println("cookieValue:" + cookieValue);
}
}
}
Y0u can refer this examle

Cookie lost on multiple requests (spring mvc + jsp)

I set my cookie in my controller, return a new modelandview, the cookie gets set. However, on any other request, the cookie is lost.
Also, when I reset the cookie to some other value, the value doesn't change when the page is loaded. It does change after page refresh and it again gets lost on any other request.
During all these multiple requests, JSESSIONID remains the same.
In controller:
Cookie locationCookie = new Cookie("locCookie", loc);
locationCookie.setMaxAge(60*60*24*365); //one year
response.addCookie(locationCookie);
return FWD_HOME;
In JSP (FWD_HOME):
<jsp:include page="/WEB-INF/jsp/fragments/header.jsp"></jsp:include>
<jsp:forward page="/HOME"></jsp:forward>
In JSP (header):
<%
Cookie cookie = null;
Cookie[] cookies = null;
cookies = request.getCookies();
String locValue = null;
if( cookies != null ){
for (int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.print(cookie.getName()+"=");
out.print(cookie.getValue()+";");
if("locCookie".equals(cookie.getName())){
locValue = cookie.getValue();
}
}
}
out.print(locValue);
%>
What am I doing wrong here?
I got the solution. along with Cookies on localhost with explicit domain, setting the path to "/" made it work.

Categories