Kaushik Lingerkar
Kaushik Lingerkar

Reputation: 449

How to create a cookie and use it in HttpURLConnection?

I have the following python code which creates a cookie and adds it to the session. What would be the equivalent java code for it using HttpURLConnection? I basically want to do a HTTP POST request using the generated cookie.

    session = requests.session()
    session.auth = (username, password)
    try:
        token = session.get(SITEMINDER_URL % server, verify=False)
        session.cookies.update(dict(SMSESSION=json.loads(token.content)['SMSESSION']))
    except Exception as ex:
        raise Exception("Failed in authenticating with siteminder", ex)
    response = session.post(api_url, headers=headers, verify=False, json=data)

Upvotes: 3

Views: 1363

Answers (4)

Gaurav Shakya
Gaurav Shakya

Reputation: 121

Try This:

    URL url = new URL("http://www.example.com");
    HttpURLConnection conn = (HttpURLConnection)url.openConnection();

    conn.setRequestProperty("Cookie", "name1=value1; name2=value2");

    conn.connect();

Upvotes: 1

Alexander Petrov
Alexander Petrov

Reputation: 9492

To get higher abstraction for Cookie use CookieManager and CookieStore classes. Here is an example:

HttpURLConnection connection
CookieManager cookieManager = new CookieManager();
HttpCookie cookie = new HttpCookie("cookieName","cookieValue");

cookieManager.getCookieStore().add(null,cookie);

connection.setRequestProperty("Cookie", String.join( ";", cookieManager.getCookieStore().getCookies()));  

Upvotes: 0

Bondavalli69
Bondavalli69

Reputation: 63

In my opinion, you can just create an HttpUrlConnection object assigning a List of Cookies as follows:

List<String> cookies = new ArrayList<>();
//Or using a map With entries: Key and value for each cookie
cookies.add("User-Agent=MyUserAgent"); //etc...
URL site = new URL("https://myurl.com");
HttpsURLConnection conn = (HttpsURLConnection) site.openConnection();
for (String string: cookies) {
        conn.setRequestProperty("Cookie", string);
}

However this is the simplest but not the best way to do so.

Upvotes: 0

Richard Sand
Richard Sand

Reputation: 674

You would use something like this:

HttpURLConnection httpconn = < some source to get a HttpURLConnection >;
String cookieName = "SMSESSION"; // note this is the default but SM can use other prefixes
String cookieValue = < your token content >;
httpurl.setRequestProperty("Cookie", cookieName + "=" + cookieValue);

Also, from the javadocs: NOTE: HTTP requires all request properties which can legally have multiple instances with the same key to use a comma-separated list syntax which enables multiple properties to be appended into a single property

Which leads me to pointing out that using the HttpUrlConnection directly is really clumsy. I recommend you look at an HTTP client library such as Apache HTTP Client http://hc.apache.org/httpcomponents-client-ga/

Upvotes: 0

Related Questions