HttpClient自定義HTTP頭


HTTP訊息可以包含許多描述訊息屬性的檔頭,例如內容長度,內容型別,授權等。 HttpClient提供了檢索,新增,刪除和列舉檔頭的方法。 在下面的教學中,我們將演示如何將自定義HTTP頭新增到HttpClient和Http請求方法。

Maven依賴關係

我們使用maven來管理依賴關係,並使用Apache HttpClient 4.5版本。 將以下依賴項新增到您的專案中。

pom.xml 檔案的內容如下 -

<?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.yiibai.httpclient.httmethods</groupId>
    <artifactId>http-get</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <url>https://memorynotfound.com</url>
    <name>httpclient - ${project.artifactId}</name>

    <dependencies>
        <!-- Apache Commons IO -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</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>

自定義HTTP頭範例

HttpClient允許我們新增,編輯,刪除或列舉http頭。 首先來看看在HttpClient上設定預設檔頭。 接下來,我們在訊息上新增自定義HTTP請求檔頭。

檔案:HttpClientRedirectHandlingExample.java -

package com.yiibai.httpdemo;

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

執行上面範例程式碼,得到以下結果 -

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.5 (Java/1.8.0_65)", 
    "X-Custom-Header": "custom header http request", 
    "X-Default-Header": "default header httpclient"
  }
}