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 的正确方法吗?还是需要设置其他参数?

4

1 回答 1

2

您可能想尝试从整个 sCookies 字符串中删除 URLEncoder.encode。cookie 格式应采用 NAME=VALUE 的形式,但通过 URLEncoding 整个字符串,您将转义 =。

于 2012-08-22T03:45:44.163 回答