通过HTTPURLConnection发送cookie

时间:2012-08-22 03:28:10

标签: java jsp servlets cookies response

我正在尝试使用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 个答案:

答案 0 :(得分:2)

您可能想尝试从整个sCookies字符串中删除URLEncoder.encode。 cookie格式应该是NAME = VALUE的形式,但是通过URLEncoding整个字符串你将逃脱=。