HttpClient 4 - Benutzerdefiniertes Cookie senden

1. Überblick

Dieses Tutorial konzentriert sich aufhow to send a Custom Cookie using the Apache HttpClient 4.

Wenn Sie tiefer graben und andere coole Dinge lernen möchten, die Sie mit dem HttpClient tun können, gehen Sie zuthe mainHttpClienttutorial.

2.1. HttpClient Nach 4.3

Im neueren HttpClient 4.3 nutzen wir die fließende Builder-API, die sowohl für die Erstellung als auch für die Konfiguration des Clients verantwortlich ist.

Zuerst müssen wir einen Cookie-Shop erstellen und unseren Beispiel-Cookie im Store einrichten:

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

Dannwe can set up this cookie store on the HttpClient using the setDefaultCookieStore() method und senden Sie die Anfrage:

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

Ein sehr wichtiges Element ist, dassdomain auf dem Cookie gesetzt werden -without setting the proper domain, the client will not send the cookie überhaupt!

2.2. HttpClient vor 4.3

Bei älteren Versionen des HttpClient (vor 4.3) wurde der Cookie-Speicher direkt aufHttpClient gesetzt:

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

Abgesehen von der Art und Weise, wie der Client erstellt wird, gibt es keinen anderen Unterschied zum vorherigen Beispiel.

Wenn das Setzen des Cookies für den gesamten HttpClient keine Option ist, können wir Anforderungen mit dem Cookie individuell mithilfe der KlasseHttpContextkonfigurieren:

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

Eine einfache Alternative zum Festlegen des Cookies in der HTTP-Anforderung wäre das Festlegen eines unformatierten Headers:

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

Dies ist natürlich viel mehrerror-prone than working with the built in cookie support. Beachten Sie beispielsweise, dass wir die Domain in diesem Fall nicht mehr festlegen - was nicht korrekt ist.

5. Fazit

Dieser Artikel zeigt, wie manwork with the HttpClient to send a custom, user controlled Cookie macht.

Beachten Sie, dass dies nicht das Gleiche ist, als wenn der HTTP-Client die von einem Server gesetzten Cookies behandelt. Stattdessen wird die Clientseite manuell auf einer niedrigen Ebene gesteuert.

Die Implementierung all dieser Beispiele und Codefragmente finden Sie inmy github project.