Apache HttpClient – Send Custom Cookie – Apache HttpClient – 发送自定义Cookie

最后修改: 2013年 12月 24日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This tutorial will focus on how to send a Custom Cookie using the Apache HttpClient.

本教程将重点介绍如何使用Apache HttpClient发送一个自定义Cookie

If you want to dig deeper and learn other cool things you can do with the HttpClient – head on over to the main HttpClient tutorial.

如果你想更深入地了解你可以用HttpClient做的其他很酷的事情–请到HttpClient教程

2. Configure Cookie Management on the HttpClient

2.在HttpClient上配置Cookie管理

2.1. HttpClient After 4.3

2.1.4.3之后的HttpClient

In the newer HttpClient 4.3, we’ll leverage the fluent builder API responsible with both constructing and configuring the client.

在较新的HttpClient 4.3中,我们将利用流畅的构建器API来负责构建和配置客户端。

First, we’ll need to create a cookie store and set up our sample cookie in the store:

首先,我们需要创建一个cookie商店,并在商店中设置我们的样本cookie。

BasicCookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
cookie.setDomain(".github.com");
cookie.setPath("/");
cookieStore.addCookie(cookie);

Then, we can set up this cookie store on the HttpClient using the setDefaultCookieStore() method and send the request:

然后,我们可以使用setDefaultCookieStore()方法在HttpClient上设置这个cookie存储,并发送请求。

@Test
public void whenSettingCookiesOnTheHttpClient_thenCookieSentCorrectly() 
  throws ClientProtocolException, IOException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();

    final HttpGet request = new HttpGet("http://www.github.com");

    response = client.execute(request);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

A very important element is the domain being set on the cookie – without setting the proper domain, the client will not send the cookie at all!

一个非常重要的元素是在cookie上设置的domain如果没有设置适当的domain,客户端将根本不会发送cookie!。

Also, depending on the exact version you use, you may also need to set:

此外,根据你使用的具体版本,你可能还需要设置。

cookie.setAttribute(ClientCookie.DOMAIN_ATTR, "true");

2.2. HttpClient Before 4.3

2.2.4.3之前的HttpClient

With older versions of the HttpClient (before 4.3) – the cookie store was set directly on the HttpClient:

对于老版本的HttpClient(4.3之前)–cookie存储是直接在HttpClient上设置的。

@Test
public void givenUsingDeprecatedApi_whenSettingCookiesOnTheHttpClient_thenCorrect() 
  throws ClientProtocolException, IOException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    DefaultHttpClient client = new DefaultHttpClient();
    client.setCookieStore(cookieStore);

    HttpGet request = new HttpGet("http://www.github.com");

    response = client.execute(request);
    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

Other than the way the client is built, there’s no other difference from the previous example.

除了客户端的构建方式外,与之前的例子没有其他区别。

3. Set the Cookie on the Request

3.在请求中设置Cookie

If setting the cookie on the entire HttpClient is not an option, we can configure requests with the cookie individually using the HttpContext class:

如果在整个HttpClient上设置cookie不是一种选择,我们可以使用HttpContext类单独配置带有cookie的请求。

@Test
public void whenSettingCookiesOnTheRequest_thenCookieSentCorrectly() 
  throws ClientProtocolException, IOException {
    BasicCookieStore cookieStore = new BasicCookieStore();
    BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", "1234");
    cookie.setDomain(".github.com");
    cookie.setPath("/");
    cookieStore.addCookie(cookie);
    instance = HttpClientBuilder.create().build();

    HttpGet request = new HttpGet("http://www.github.com");

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(HttpClientContext.COOKIE_STORE, cookieStore);
    // localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore); // before 4.3
    response = instance.execute(request, localContext);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

4. Set the Cookie on the Low Level Request

4.在低级别请求上设置Cookie

A low level alternative of setting the cookie on the HTTP Request would be setting it as a raw Header:

在HTTP请求上设置cookie的一个低级替代方法是将其设置为一个原始的Header。

@Test
public void whenSettingCookiesOnARequest_thenCorrect() 
  throws ClientProtocolException, IOException {
    instance = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("http://www.github.com");
    request.setHeader("Cookie", "JSESSIONID=1234");

    response = instance.execute(request);

    assertThat(response.getStatusLine().getStatusCode(), equalTo(200));
}

This is of course much more error-prone than working with the built in cookie support. For example, notice that we’re no longer setting the domain in this case – which is not correct.

当然,这比使用内置的cookie支持要容易得多错误。例如,注意到我们在这种情况下不再设置域名–这是不正确的。

5. Conclusion

5.结论

This article illustrated how to work with the HttpClient to send a custom, user controlled Cookie.

这篇文章说明了如何与HttpClient合作来发送一个自定义的、用户控制的Cookie

Note that this is not the same as letting the HttpClient deal with the cookies set by a server. Instead, it’s controlling the client side manually at a low level.

请注意,这与让HttpClient处理服务器设置的cookie是不同的。相反,它是在低水平上手动控制客户端。

The implementation of all these examples and code snippets can be found in my github project.

所有这些例子和代码片段的实现都可以在我的github项目中找到。