Apache HttpClient 4.5 Custom HTTP Headers Example
An HTTP message can contain a number of headers describing properties of the message such as content length, content type, authorization and so on. HttpClient provides methods to retrieve, add, remove and enumerate headers. In the following tutorial we’ll show how to add custom HTTP Headers to the HttpClient and Http request method.
Maven dependencies
We use maven to manage our dependencies and are using Apache HttpClient version 4.5. Add the following dependency to your project.
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.memorynotfound.apache.httpclient</groupId> <artifactId>custom-headers</artifactId> <version>1.0.0-SNAPSHOT</version> <url>https://memorynotfound.com</url> <name>httpclient - ${project.artifactId}</name> <dependencies> <!-- Apache HttpClient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
Custom HTTP Headers Example
The HttpClient allows us add, edit, remove or enumerate http headers. First we’ll look at setting default headers on the HttpClient. Next, we add custom HTTP request headers on the message.
package com.memorynotfound.httpclient; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHeaders; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.RequestBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicHeader; import org.apache.http.util.EntityUtils; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * This example demonstrates how to use custom http headers. */ public class HttpClientCustomHeadersExample { public static void main(String... args) throws IOException { // create custom http headers for httpclient List<Header> defaultHeaders = Arrays.asList( new BasicHeader("X-Default-Header", "default header httpclient")); // setting custom http headers on the httpclient CloseableHttpClient httpclient = HttpClients .custom() .setDefaultHeaders(defaultHeaders) .build(); try { // setting custom http headers on the http request HttpUriRequest request = RequestBuilder.get() .setUri("http://httpbin.org/headers") .setHeader(HttpHeaders.CONTENT_TYPE, "application/json") .setHeader(HttpHeaders.FROM, "https://memorynotfound.com") .setHeader("X-Custom-Header", "custom header http request") .build(); System.out.println("Executing request " + request.getRequestLine()); // Create a custom response handler ResponseHandler<String> responseHandler = response -> { int status = response.getStatusLine().getStatusCode(); if (status >= 200 && status < 300) { HttpEntity entity = response.getEntity(); return entity != null ? EntityUtils.toString(entity) : null; } else { throw new ClientProtocolException("Unexpected response status: " + status); } }; String responseBody = httpclient.execute(request, responseHandler); System.out.println("----------------------------------------"); System.out.println(responseBody); } finally { httpclient.close(); } } }
Output
The previous application prints the following info to the console. As you can see, all the previous headers are added to the message.
Executing request GET http://httpbin.org/headers HTTP/1.1 ---------------------------------------- { "headers": { "Accept-Encoding": "gzip,deflate", "Connection": "close", "Content-Type": "application/json", "From": "https://memorynotfound.com", "Host": "httpbin.org", "User-Agent": "Apache-HttpClient/4.5.3 (Java/1.8.0_20)", "X-Custom-Header": "custom header http request", "X-Default-Header": "default http header httpclient" } }
Download
From:一号门
COMMENTS