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



我正在使用HttpComponents 4.5.5,我正在尝试通过post-request将从以前的get-request获得的cookie发送到同一域的另一端。由于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);
}

控制台显示问题:

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 的文档

问题是饼干本身。设置了httponly和安全标志。所以它不能在HTTP上工作。

另请参阅会话 Cookie secure/httponly

相关内容

  • 没有找到相关文章