CookieStore中的Cookie未发送--Apache HttpComponents 4.5.5

时间:2018-04-12 18:24:36

标签: java cookies session-cookies apache-httpclient-4.x apache-httpcomponents

我正在使用HttpComponents 4.5.5并且我正在尝试通过post-request将我从之前的get-request获得的cookie发送到同一域的另一端。由于session_id,我需要发送收到的cookie。

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);
}

控制台显示问题:

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]]

来自get-request的cookie存储在CookieStore中,但是当涉及到post-request时,它不会被发送到服务器。因此,服务器发送一个新cookie,用于替换CookieStore中的现有cookie。

我不知道我错过了什么。我已经检查了使用HttpComponents 4.5处理cookie的文档

1 个答案:

答案 0 :(得分:0)

问题在于cookie本身。 httponly&安全标志已设定。所以它不会在http。

上工作

另见Session Cookie secure/httponly