我如何使用球衣客户端获得 'jsessionid'?

how can i get 'jsessionid' using jersey client?

我正在使用 jersey-client 1.19.4 来测试我的网络应用程序。 如果我用邮递员测试,我可以在 'send' 操作后找到 cookie "JSESSIONID"。我可以在 ClientResponse.toString() 中找到 'jsessionid=...',但是 ClientResponse.getCookies() returns 什么都没有。

WebResource webResource = client.resource(someUrl);
FormDataMultiPart   formData = new FormDataMultiPart();
formData.bodyPart(new FormDataBodyPart("userId", userId));
formData.bodyPart(new FormDataBodyPart("uPasswd", uPasswd));
ClientResponse  response = webResource.accept("*/*").type(MediaType.MULTIPART_FORM_DATA_TYPE).post(ClientResponse.class, formData);
System.out.println("response: " + response.toString());  // 'jsessionid' found here
List<NewCookie> cookies = response.getCookies();
System.out.println("# of cookies: " + cookies.size());  // prints "# of cookies: 0"

如何从 ClientResponse 获取 "JSESSIONID"?

JSESSIONID 可以通过几种不同的方式设置。根据 JSR-000315 Java Servlet 3.0 Final Release,第 7.1 章会话跟踪机制,可以使用以下内容:

  • Cookies
  • SSL Sessions
  • URL Rewriting

在您的情况下,似乎正在使用 URL 重写。两个最常见的原因是:

  • 服务器配置为不发出 cookie
  • 您的客户端不支持 cookies

由于您在使用 Postman 时获得了 cookie,这很可能意味着您的 Jersey Client 不处理 cookie。使用 jersey-apache-client as per this answer.

将其与 Apache HttpClient 集成的一种方法

来自邮件列表:

http://jersey.576304.n2.nabble.com/Session-Handling-not-working-with-Jersey-Client-td4519663.html

The Jersey client by default uses HttpURLConnection that does not
support cookie management (and thus sessions).

You need to switch to using the Apache HTTP client support.

Then set the following property to true: PROPERTY_HANDLE_COOKIES

DefaultApacheHttpClientConfig config = new  
DefaultApacheHttpClientConfig(); config
    .setProperty("com.sun.jersey.impl.client.httpclient.handleCookies",  
        true);
ApacheHttpClient c = ApacheHttpClient.create(config);

Plus you can also use authorization with the Apache HTTP client
integration.

  DefaultApacheHttpClientConfig config = new   DefaultApacheHttpClientConfig();
  config.getState().setCredentials(null, null, -1, "foo", "bar");
  ApacheHttpClient c = ApacheHttpClient.create(config);
  WebResource r = c.resource("http://host/base");
  String s = r.get(String.class);
  s = r.post(String.class, s);