HttpClient series - Basics (b)

Brief

Under today began to introduce the basics Second, the main contents of the interrupt request, redirection.

Interrupt Request

How to use the Apache HttpClient 4 cancel HTTP request.

This is particularly useful for downloading large files may request or a long-running, otherwise the request will unnecessarily consume bandwidth and connectivity.

GET request to suspend

To abort a request, the client can simply use:

request.abort();
复制代码

This will ensure that clients do not have to use the entire request to release the connection:

@Test
public void test() 
  throws ClientProtocolException, IOException {
    HttpClient instance = HttpClients.custom().build();
    HttpGet request = new HttpGet(SAMPLE_URL);
    HttpResponse response = instance.execute(request);
 
    try {
        System.out.println(response.getStatusLine());
        request.abort();
    } finally {
        response.close();
    }
}
复制代码

Redirect ban

By default, the HTTP specification, HttpClient will automatically follow redirects

For some use cases, it may be not in question, but certainly does not require the use cases will appear. Now we will look at how to change the default behavior and stop the redirect.

Before HttpClient 4.3

In the old version of HttpClient (prior to 4.3), we can configure the client to use redirection to perform the operation, as follows:

@Test
public void test() 
  throws ClientProtocolException, IOException {
    DefaultHttpClient instance = new DefaultHttpClient();
 
    HttpParams params = new BasicHttpParams();
    params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
    // HttpClientParams.setRedirecting(params, false); // alternative

    HttpGet httpGet = new HttpGet("http://localhost:8080");
    httpGet.setParams(params);
    CloseableHttpResponse response = instance.execute(httpGet);
 
    assertThat(response.getStatusLine().getStatusCode(), equalTo(301));
复制代码

Note that redirection can be used to configure the behavior of backup API, rather than using the actual original http.protocol.handle-redirects set parameters:

HttpClientParams.setRedirecting(params, false);
复制代码

Also note that if you disable subsequent redirection, we can now check whether the Http response status code is indeed 301 Moved Permaned - should be.

After HttpClient 4.3

HttpClient 4.3 introduces a clearer, higher-level API to build and configure the client:

@Test
public void test() 
  throws ClientProtocolException, IOException {
    HttpClient instance = HttpClientBuilder.create().disableRedirectHandling().build();
HttpResponse response = instance.execute(new HttpGet("http://localhost:8080"));
    assertThat(response.getStatusLine().getStatusCode(), equalTo(301));

复制代码

PS: This new API uses redirection to configure the behavior of the entire client - not just a single request.

Custom Hearder

The requirements set Hearder (4.3 and above)

HttpClient 4.3 introduces a new API for constructing request - RequestBuilder. To set the Header, we will use the method on setHeader builder:

HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
  .setUri(SAMPLE_URL)
  .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  .build();
client.execute(request);
复制代码

The requirements set Hearder (before 4.3)

In the previous version 4.3 HttpClient, we can use a simple setHeader call set any custom headers in the request:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(SAMPLE_URL);
request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
client.execute(request);
复制代码

We can see that we will direct Content-Type is set to a custom value --JSON on request.

On the client to set the default header

We can also be configured as a client's own default headers, instead of setting a header on each request:

Header header = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
List<Header> headers = Lists.newArrayList(header);
HttpClient client = HttpClients.custom().setDefaultHeaders(headers).build();
HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();
client.execute(request);
复制代码

At the same time (e.g., a custom application headers), which is useful when the header of all requests require phase.

summary

This article describes the HttpClient of the interrupt request, disable trace HTTP redirects, custom Header knowledge, I hope for your help.

Guess you like

Origin juejin.im/post/5d0c8c03e51d4556dc29364b