带有“ Cookie”的HttpURLConnection addRequestProperty导致逗号分隔的Cookie字符串?

时间:2019-04-04 09:50:48

标签: java cookies httpurlconnection

我必须从Java代码模拟浏览器的行为。

在将请求发布到服务器之前,我必须在请求上设置两个cookie。

我这样做:

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

在服务器日志上,我看到“ IDS_SSO_ID” cookie被检索为“ onething,JSESSIONID”,这将导致错误。

请注意,我无权访问服务器,也无权访问服务器的源代码,只有日志。

我应该如何使用HttpURLConnection设置cookie?


因此,我创建了一个小型演示;如果我使用“ addRequestProperty”,则会发送不正确的Cookie标头:

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标头值为: JSESSIONID = akarmi123,IDS_SSO_ID = netudd321

如果我使用“ setRequestProperty”并手动构造Cookie头,则会发送正确的Cookie头:

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标头值为: JSESSIONID = akarmi123; IDS_SSO_ID = netudd321

奇怪的是,网络上的许多资源(以及SO中的资源)也推荐了我的第一种方法-对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

但是看来他们错了...

1 个答案:

答案 0 :(得分:1)

一种可能性是通过执行以下操作来强制cookie字符串的正确串联:

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

您所描述的行为在我看来是意外行为。