1

我的 HttpServletRequest.getCookies() 没有返回整个 cookie 值。cookie 值是另一个键值对,因此可能会弄乱解析。我需要知道如何解决这个问题。

所以这是背景。我正在使用新的 apache2.4 mod_auth_form,它通过在 cookie 中设置用户名和密码来进行身份验证。cookie 看起来像这样:“session=private-user=myUser&private-pw=myPass”

我在 Apache 上设置了一个代理,以便将某些 REST 调用传递给一个 tomcat 服务,在那里我有一个 Jersey REST 类在等待它们。

我可以在浏览器中看到 cookie。我还可以在 php.ini 中看到完整的 cookie。但是,在我的 java 类中,HttpServletRequest 具有“会话”cookie,但值只是“私人用户”,而不是我期望的“私人用户=myUser&private-pw=myPass”。

我最好的猜测是带有 = 和 & 符号的键值对搞砸了解析。我怎样才能获得完整的原始 cookie 价值?

如果重要的话,这是我的java代码:

private String getAuthenticatedUser(HttpServletRequest httpRequest) {
        String user = null;
        Cookie[] cookies = httpRequest.getCookies();
        for(Cookie cookie : cookies) {
            System.out.println(cookie.getValue());
        }
}

谢谢

4

2 回答 2

0

我使用 Jersey 的 @CookieParam 注释找到了一种解决方法。

@GET
@Path("/")
public Response myRestCall(@CookieParam("session") String sessionValue) {
  System.out.println(sessionValue);
}

Jersey 似乎在解析这种类型的键值 cookie 方面做得更好,并按我的预期返回了“private-user=myUser&private-pw=myPass”。

于 2013-03-05T18:20:52.107 回答
0

在将值设置到 cookie 之前,使用 URLEncoder 对值进行编码。

String s = new String("private-user=myUser&private-pw=myPass");
String encoded = URLEncoder.encode(s);

并使用 URLDecoder 将其解码回原始值

URLDecoder.decode(encoded);
于 2013-03-05T11:09:37.300 回答