Set value for a cookie

Asked

Viewed 268 times

2

I intend to change a cookie value, I’m using:

public static void main(String[] args) throws Exception {
    URL url;
    HttpURLConnection conn;

    url = new URL("http://google.pt");

    conn = (HttpURLConnection) url.openConnection();

    conn.addRequestProperty("Cookie", "COOKIE=QUALQUERCOISA");
    conn.setRequestProperty("Cookie", "COOKIE=QUALQUERCOISA");

    for (int i = 1; (conn.getHeaderFieldKey(i)) != null; i++) {
        System.out.println(conn.getHeaderField(i));
    }
}

The output is:

Tue, 18 Aug 2015 17:11:23 GMT  
-1  
private, max-age=0  
text/html; charset=ISO-8859-1  
CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."  
gws  
1; mode=block  
SAMEORIGIN  
PREF=ID=1111111111111111:FF=0:TM=1439917883:LM=1439917883:V=1:S=_eDy4EFOKwUQbSmv; expires=Thu, 17-Aug-2017 17:11:23 GMT; path=/; domain=.google.pt  
NID=70=bVTWaWrDKKfMTdhKERZr8NUlf6hYUzt4y1Sw3umSgjnWubydTDGnDxryyv75KWQPCQkDkJSNStJbwzL7fQPtgZnVRvmQidhvp_wUqBsA679hNpC-kIlzK3sW2Lo8OWA0; expires=Wed, 17-Feb-2016 17:11:23 GMT; path=/; domain=.google.pt; HttpOnly  
none  
Accept-Encoding  
chunked  

Does not add new cookie value.

  • Solved the problem with: Conn = (Httpurlconnection) url.openConnection(); Conn.setRequestMethod("POST"); Conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); Conn.setDoOutput(true; Conn.setRequestProperty("Cookie","JSESSIONID=" + string_com_jsessionid); Conn.connect();

2 answers

1

I solved the problem with:

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setDoOutput(true);
        conn.setRequestProperty("Cookie","JSESSIONID=" + string_com_jsessionid);
        conn.connect();

...

1

Pay pick up the Cookies to Response header and charge to cookieManager try:

static final String COOKIES_HEADER = "Set-Cookie";
HttpURLConnection connection = ... ;
static java.net.CookieManager msCookieManager = new java.net.CookieManager();

Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

if(cookiesHeader != null)
{
    for (String cookie : cookiesHeader) 
    {
      msCookieManager.getCookieStore().add(null,HttpCookie.parse(cookie).get(0));
    }               
}

Then to grab the cookie from the cookieManager and load it into the Connection:

if(msCookieManager.getCookieStore().getCookies().size() > 0)
{
    //While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
    connection.setRequestProperty("Cookie",
    TextUtils.join(";",  msCookieManager.getCookieStore().getCookies()));    
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.