Search code examples
javajersey-client

how can i get 'jsessionid' using jersey client?


I'm using jersey-client 1.19.4 to test my web application. If I test with postman, I can find the cookie "JSESSIONID" after 'send' action. And I can find 'jsessionid=...' in ClientResponse.toString(), But ClientResponse.getCookies() returns nothing.

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"

How can I get "JSESSIONID" from ClientResponse?


Solution

  • JSESSIONID can be set in few different ways. As per JSR-000315 Java Servlet 3.0 Final Release, chapter 7.1 Session Tracking Mechanisms, following can be used:

    • Cookies
    • SSL Sessions
    • URL Rewriting

    In your case it appears that URL Rewriting is being used. The two most common reasons being:

    • The server is configured not to issue cookies
    • Your client doesn't support cookies

    Since you get the cookie while using Postman it most likely means that your Jersey Client doesn't handle cookies. One way to integrate it with Apache HttpClient using jersey-apache-client as per this answer.