HttpURLConnection addRequestProperty with “Cookie” resulting in comma separated Cookie string?

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 01:19:07

问题


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...


回答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.



来源:https://stackoverflow.com/questions/55512910/httpurlconnection-addrequestproperty-with-cookie-resulting-in-comma-separated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!