0

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

https://www.programcreek.com/java-api-examples/?class=java.net.HttpURLConnection&method=addRequestProperty

http://www.massapi.com/method/ad/addRequestProperty-2.html

But it seems that they are wrong...

riskop
  • 1,693
  • 1
  • 16
  • 34

1 Answers1

1

A possibility would be to enforce the right concatenation of the cookie strings by doing the following:

conn.addRequestProperty("Cookie", "JSESSIONID=" + "otherthing" + ";IDS_SSO_ID=" + "onething");

The behavior described by you looks to me as an unintended behavior.

MansenC
  • 101
  • 1
  • 5
  • indeed, if I manually construct the 'Cookie' request header as you suggested, then everything works. Note that in this case I'd rather use setRequestProperty(...) btw. – riskop Apr 04 '19 at 13:25