How to set cookie from CookieManager when using HttpUrlConnection? - java

I'm perform a http request with some cookie, My code like this:
HttpURLConnection conn = (HttpURLConnection) u.openConnection();
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
cookieManager.getCookieStore().add(....);//here to set cookie
CookieHandler.setDefault(cookieManager);
// do request in following
But I can't find my cookie by fiddler. I have search many questions in stackoverflow, none of them work through. So, please help me to find the way to set cookie.
P.S. I don't want to use Cookie header.

finally , I found the problem , CookieHandler.setDefault() should be call before any Http operation, in my code ,it should before u.openConnection().

Related

How to get Cookies with HttpURLConnection in Java?

When I use HttpURLConnection and try con.getHeaderField("Set-Cookie") I get this response:
__cfduid=1111111aaaaaa; expires=Wed, 19-Dec-18 06:19:46 GMT; path=/; domain=.site.com; HttpOnly
But the browser cookies are:
__cfduid=1111111aaaaaa; _ym_uid=000000000; PHPSESSID=zzzzzzzz; _ym_isad=1; key=555
How I can get the FULL cookie, using HttpURLConnection? The most important cookie for me is key.
The value of Set-cookie header modify or append new value to Cookies in browser. And browser delete expired cookie from cookies. The assembling work completed by browser.
When request web in java, programmer need assemble 'full' cookies by Set-cookie header in single or multi responses.
If you use HttpURLConnection, you can use CookieManager
This is an example
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
URL url = new URL("https://stackoverflow.com");
URLConnection connection = url.openConnection();
connection.getContent();
List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
for (HttpCookie cookie : cookies) {
System.out.println(cookie.getDomain());
System.out.println(cookie);
}
When you send HTTP request, CookieManager will auto fill Cookie Header. And, the value can be directly achieved from CookieManger by domain.

Build and use Cookie for token based authentication to gain access to api through openAM

Please excuse me if any of this sounds very stupid or inexperienced, however I have looked everywhere else and haven't been able to find a simple explanation as to how to properly implement this.
So far I have made a restful call to a server running on openAm; the call sends my user name and password credentials and returns to me a secure token. I then need to make another restful call to request certain json files in their api.
I understand that in my second restful call I need to somehow embed the token with it so the server knows that I am allowed to access the requested data. My question is what is the proper way to go about this. I have found/heard of multiple possibilities such as passing it in the header, parameters, or as a cookie, but each time my request is redirected to the log in url instead of returning my request.
From my understanding it appears the cookie method works best (if I'm wrong then please post a different method). So for openAm authentication, how do I properly build a cookie with my token. Once the cookie is built how do I embed that into the connection. Do I need to make a whole new connection or can I redirect my original connection with the cookie? Any help or advice is greatly appreciated.
Some of my code, using HttpURLConnection:
//takes url and builds our connection
String url = "http://some.url.net/openam/json/authenticate";
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("X-OpenAM-Username", name);
connection.setRequestProperty("X-OpenAM-Password", pass);
connection.setRequestProperty("Content-Type", "application/json");
//takes in the connections response
BufferedReader in = new BufferedReader(new InputStreamReader(response, "UTF-8"));
String output = in.readLine();
//this is to cut the token out of the response
int i = 14;
while(true){
if (output.charAt(i)=='"'){
break;
}
i++;
}
String token = output.substring(14,i);
//build our new connection and second call
url = "https://other.url.net/api/v1/resource/attributes";
HttpURLConnection request_conn = (HttpURLConnection) new URL(url).openConnection();
/*
request_conn.setRequestProperty("iPlanetDirectoryPro", token);
request_conn.setRequestMethod("POST");
request_conn.connect();
*/ //Tried to put the token through the header, doesnt work
/*
Cookie cookie;
cookie = new Cookie("iPlanetDirectoryPro", token);
cookie.setDomain(".di2e.net");
cookie.setPath("/");
cookie.setSecure(true);
request_conn.addCookie(cookie);//addCookie() doesnt work for a urlConection?
*/ //Tried building the cookie and adding it to the new conection

How to send cookies over URL connection

I am trying to set Cookies and request headers via URL connection. Here is the client side code
UUID = request.getHeader("UUID");
conn.addRequestProperty("Cookie", iPlanetDirectoryPro);
conn = url.openConnection();
conn.setDoOutput(true);
objOstr = new OutputStreamWriter(conn.getOutputStream());
objOstr.write(res);
One server side i am trying a retrieve the cookie using "iPlanetDirectoryPro" as the cookie name. But i am getting null. What is the mistake i am doing here?
If i set as conn.addRequestProperty("iPlanetDirectoryPro", iPlanetDirectoryPro); then what is the difference between cookie-and-string-in-request-header https://stackoverflow.com/questions/21226475/difference-between-cookie-and-string-in-request-header
Try using:
conn.getRequestProperty("Cookies");
See the doc.

Android setRequestProperty in a url.openConnection()

I have an Android app that need to set a requestproperty in a connection. Here is my code:
URL url = new URL(sUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("cookie", cookievalue);
connection.connect();
When I call the setRequestProperty method it launch the exception:
java.lang.IllegalStateException: Cannot set request property after connection is made
Is there a way to create the connection to the file without using the url.openConnection() ?
Here url.openCOnnection() will open new connection to the resource referred to by this URL.
Here you again opening a connection by calling url.connect() method. So remove that
Check this.. for the sample example...
You could try to use the CookieManager mentioned in http://developer.android.com/reference/java/net/HttpURLConnection.html
Set your cookie to CookieManager
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpCookie cookie = new HttpCookie("lang", "fr");
cookie.setDomain("twitter.com");
cookie.setPath("/");
cookie.setVersion(0);
cookieManager.getCookieStore().add(new URI("http://twitter.com/"), cookie);
Source: http://developer.android.com/reference/java/net/HttpURLConnection.html
Use url.openConnection() after you set your cookie.

Java get Session Cookies

Getting header fields from a URLConnection doesn't get session cookies for me.
When I use CookieManager I can get session cookies from a URL:
CookieManager manager = new CookieManager();
manager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
CookieHandler.setDefault(manager);
URLConnection con = url.openConnection();
con.getContent();
CookieStore cookieJar = manager.getCookieStore();
List<HttpCookie> cookies = cookieJar.getCookies();
This is fine, but I need to send a POST request. So I am writing to the URLConnection's output stream. My question is how to get the session cookies after sending the POST request.
Try using the same CookieManager object with your first and subsequent requests using URLConnection.

Categories

Resources