I'm using HttpComponents 4.5.5 and I'm trying to send the cookie which I got from a previous get-request to another side of the same domain via post-request. I need to send the received cookie because of the session_id.
private static final String url = "http://test.asdf.com:2222";
public static void main(String[] args) throws ClientProtocolException, IOException, JSONException {
startGuide();
}
public static void startGuide()
throws ClientProtocolException, IOException, UnsupportedCharsetException, ParseException, JSONException {
// HttpClient
CloseableHttpResponse closeableHttpResponse;
CookieStore cookieStore = new BasicCookieStore();
RequestConfig globalConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();
CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore)
.setDefaultRequestConfig(globalConfig).build();
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(cookieStore);
// ***************************************************************************************************
// HttpGet
HttpGet httpGet = new HttpGet(url + "/" + "site1");
httpGet.addHeader("accept", "application/json");
// Response
closeableHttpResponse = httpClient.execute(httpGet, context);
String response = EntityUtils.toString(closeableHttpResponse.getEntity());
// Test
System.out.println("RES: " + "site1" + " --> " + response);
System.out.println("RES: " + "cookie" + " --> " + cookieStore);
// ***************************************************************************************************
// HttpPost
HttpPost httpPost = new HttpPost(url + "/" + "site2");
// Response
closeableHttpResponse = httpClient.execute(httpPost, context);
response = EntityUtils.toString(closeableHttpResponse.getEntity());
// Test
System.out.println("RES: " + "site2" + " --> " + response);
System.out.println("RES: " + "cookie" + " --> " + cookieStore);
}
The Console shows the problem:
RES: site1 --> Well done!
RES: cookie --> [[version: 0][name: session_id][value: 3338009c638f990d5ef1ce4daea27fa48cba5287][domain: test.asdf.com][path: /][expiry: Thu Apr 12 20:52:30 CEST 2018]]
RES: site2 --> Where's your cookie!???
RES: cookie --> [[version: 0][name: session_id][value: 5ac5dfcfe6fcfc3468bfbbc5bdbd099a83cc3e3c][domain: test.asdf.com][path: /][expiry: Thu Apr 12 20:52:30 CEST 2018]]
The cookie from the get-request gets stored in the CookieStore but when it comes to the post-request it isn't sent to the server. So the server sends a new cookie which replaces the existing one in CookieStore.
I don't know what I'm missing. I already checked the documentation of handling cookies with HttpComponents 4.5