IAmYourFaja
IAmYourFaja

Reputation: 56912

HttpClient 4.x: how to retain cookies across multiple requests?

I need to use Apache HttpClient (4.x) to make 3 consecutive web calls and essentially log me into my app programmatically:

  1. An HTTP GET to a login page (http://myapp01.example.com)
  2. The server will respond to this GET with a response cookie "JSESSIONID"
  3. An HTTP POST to the same page (using the same JSESSIONID as a request cookie)
  4. The server now authenticates me and validates the JSESSIONID.
  5. An HTTP GET to a different page under the same domain (http://myapp01.example.com/fizz), again using the same JSESSIONID as a request cookie

The first GET's response will contain a cookie named JSESSIONID. The POST will then log me in to the server (sending username and password data in the POST request body). This POST will also send (Set-Cookie) the JSESSIONID cookie received from the first GET. If my logins are successful, the JSESSIONID will now be authenticated, and I am logged in. I can then make the 2nd GET call (still using the same JSESSIONID) to /fizz which is ordinarily an authenticated URL.

Can this be done in HttpClient 4? I see there is a method HttpClient.getCookieStore(). but this seems to only store cookies per GET/POST/PUT/etc.

Any ideas as to how I can get this holding cookies across multiple requests, such that any cookies returned by the server are then added to subsequent requests?

Upvotes: 1

Views: 3566

Answers (1)

ok2c
ok2c

Reputation: 27538

Apache HttpClient takes care of that automatically (since version 2)

Upvotes: 3

Related Questions