使用HTTPURLConnection发送Cookie

3

我正在尝试使用HTTPURLConnection类打开与JSP的连接并从servlet接收响应。在JSP中设置了响应头需要在servlet中读取。

以下是代码示例

String strURL = "http://<host>:<port>/<context>/mypage.jsp";
String sCookies = getCookie();//method to get the authentication cookie(**SSOAUTH**) and its value for the current logged in user

URL url = new URL(strURL);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Cookie", URLEncoder.encode(sCookies, "UTF-8"));
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);

DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
out.writeBytes("lang=en");
out.flush();
out.close();

 //reading the response received from JSP and retrieve header value
response.write(urlConnection.getHeaderField("commAuth") + "<br />");

问题在于传递的SSOAUTH cookie没有发送到JSP页面。如果我发送UID/PWD而不是cookie,就会成功通过身份验证并正确发送响应。
urlConnection.setRequestProperty("username", "testuser");
urlConnection.setRequestProperty("password", "testpwd");

这是通过HTTPURLConnection发送cookie的正确方式吗?还是需要设置其他参数?
1个回答

2
您可以尝试将URLEncoder.encode从整个sCookies字符串中移除。 cookie格式应该是NAME=VALUE,但通过对整个字符串进行URLEncoding,您将转义=符号。

我已经移除了编码并将其修改为urlConnection.setRequestProperty("Cookie", URLEncoder.encode(sCookies, "UTF-8"));但是这并没有产生任何区别。 - Contact Rao
我在考虑:urlConnection.setRequestProperty("Cookie", sCookies);,因为对url进行编码JSESSIONID=SOMETHING会转换成JSESSIONID%3DSOMETHING,可能不是有效的。此外,当你说它不起作用时,是没有发送任何内容还是cookie没有被正确设置?你能否查看是否有任何Set-Cookie头被发送(通过服务器调试或类似wireshark的流量查看)? - jcern

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接