I have to emulate browser behaviour from Java code.
I have to set two cookies on a request before posting it to the server.
I do this:
HttpURLConnection conn = ...
...
conn.addRequestProperty("Cookie", "IDS_SSO_ID=" + "onething");
conn.addRequestProperty("Cookie", "JSESSIONID=" + "otherthing"));
...
conn.close();
On the server logs I see that the 'IDS_SSO_ID' cookie is retrieved as "onething, JSESSIONID", which causes an error.
Note that I have no access to the server nor the server's source code, I only have the logs.
How should I set cookies using HttpURLConnection?
So, I've created a small demonstration; If I use 'addRequestProperty' then an incorrect cookie header is sent:
URL url = new URL("https://en0hphl04qcwvf.x.pipedream.net/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("Cookie", "JSESSIONID=akarmi123");
conn.addRequestProperty("Cookie", "IDS_SSO_ID=netudd321");
byte[] bytes = StreamUtils.copyToByteArray(conn.getInputStream());
System.out.println("response: " + new String(bytes));
conn.disconnect();
cookie header value is: JSESSIONID=akarmi123, IDS_SSO_ID=netudd321
If I use 'setRequestProperty' and manually construct the cookie header, then a correct cookie header is sent:
conn = (HttpURLConnection) url.openConnection();
conn.setRequestProperty("Cookie", "JSESSIONID=akarmi123; IDS_SSO_ID=netudd321");
bytes = StreamUtils.copyToByteArray(conn.getInputStream());
System.out.println("response: " + new String(bytes));
conn.disconnect();
cookie header value is: JSESSIONID=akarmi123; IDS_SSO_ID=netudd321
The strange thing is, that a lot of resources in the web (and here in SO too) recommends my first approach -- multiple calls on addRequestProperty(...):
How to set Cookies at Http Get method using Java
https://www.codota.com/code/java/methods/java.net.URLConnection/addRequestProperty
http://www.massapi.com/method/ad/addRequestProperty-2.html
But it seems that they are wrong...