【问题标题】:Send cookies over HTTPURLConnection通过 HTTPURLConnection 发送 cookie
【发布时间】:2012-08-17 10:52:48
【问题描述】:

我正在尝试使用 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 的正确方式吗?还是有其他需要设置的参数?

【问题讨论】:

    标签: java jsp servlets cookies response


    【解决方案1】:

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

    【讨论】:

    • 我把Encoding去掉,修改为urlConnection.setRequestProperty("Cookie", URLEncoder.encode(sCookies, "UTF-8"));但这没有任何区别。
    • 我在想:urlConnection.setRequestProperty("Cookie", sCookies);因为 urlencoding JSESSIONID=SOMETHING 会将其转换为 JSESSIONID%3DSOMETHING 并且可能无效。另外,当您说它不起作用时,是什么都没有发送,还是 cookie 设置不正确?您能否查看是否正在发送任何 Set-Cookie 标头(通过在服务器上调试或通过诸如 wireshark 之类的东西查看流量)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-31
    • 1970-01-01
    • 2014-06-25
    相关资源
    最近更新 更多