Set value for a cookie

2

I want to change a value in cookie, I am 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 the new cookie value.

    
asked by anonymous 18.08.2015 / 19:15

2 answers

1

Pay for Cookies to response header and load 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 get 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()));    
}
    
18.08.2015 / 20:35
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();

...

    
20.08.2015 / 10:40