我如何使用球衣客户端获取“ jsessionid”?

时间:2018-07-31 08:21:57

标签: java jersey-client

我正在使用jersey-client 1.19.4测试我的Web应用程序。 如果我使用邮递员进行测试,则可以在“发送”操作后找到Cookie“ JSESSIONID”。而且我可以在ClientResponse.toString()中找到“ jsessionid = ...”,但是ClientResponse.getCookies()却什么也不返回。

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”?

2 个答案:

答案 0 :(得分:1)

JSESSIONID可以通过几种不同的方式进行设置。根据{{​​3}}的第7.1节“会话跟踪机制”,可以使用以下内容:

  
      
  • 饼干
  •   
  • SSL会话
  •   
  • URL重写
  •   

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

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

由于您在使用Postman时获得了cookie,因此很可能意味着您的Jersey客户端不处理cookie。使用jersey-apache-client JSR-000315 Java Servlet 3.0 Final Release将其与Apache HttpClient集成的一种方法。

答案 1 :(得分:1)

从邮件列表中:

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

  

默认情况下,Jersey客户端使用不使用的HttpURLConnection
  支持cookie管理(从而支持会话)。

     

您需要切换为使用Apache HTTP client支持。

     

然后将以下属性设置为true:PROPERTY_HANDLE_COOKIES

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

此外,您还可以对Apache HTTP客户端使用授权
  整合。

  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);
相关问题