知识点

相关文章

更多

最近更新

更多

HttpClient 请求添加Header头部信息

2019-04-09 23:02|来源: 网路

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 -

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"
  }
}

相关问答

更多
  • 先找个抓包的工具,用浏览器走一遍.看看抓到的包都有哪些. 然后返回了什么东西. 对于你这个登录来说,肯定是会返回cookie,有一些sessionId之类的身份验证的东西.
  • 异步调用一个简单的方法是jms,比较通用的开源实现是activemq
  • 结帐http://htmlunit.sourceforge.net/ Checkout http://htmlunit.sourceforge.net/
  • 您的程序集绑定重定向是错误的。 您的iOS项目应该有一个包含以下内容的app.config文件:
    根据MSDN ,因为.NET 4.5以下实例方法是线程安全的 (感谢@ischell): CancelPendingRequests DeleteAsync GetAsync GetByteArrayAsync GetStreamAsync GetStringAsync PostAsync PutAsync SendAsync According to MSDN, since .NET 4.5 The following instance methods are thread safe (thanks @ ...
  • 您可以使用此代码前进,它适用于我.. URL url = new URL("Your URL"); HttpURLConnection httpsURLConnection = (HttpURLConnection)url.openConnection(); httpsURLConnection.setReadTimeout(15000); httpsURLConnection.setConnectTimeout(20000); httpsURLConnec ...
  • 绝对使用服务,以便您拥有API请求的中心位置。 我通常为每种类型的api提供一项服务,即/ products,/ orders等。我发现(作为例子)来自应用程序周围的组件可能会调用/ products中的端点,因此分离为服务会使代码更清洁。 我将这些服务放在CoreModule https://angular.io/guide/ngmodule-faq#coremodule中 。 以下是如何从服务使用api调用的示例,而不是直接来自组件。 https://www.concretepage.com/angul ...
  • 您需要添加Microsoft.Net.Http NuGet包。 You need to add the Microsoft.Net.Http NuGet package.
  • 如果您参考Apache HTTP客户端,则可以按照以下步骤操作: 仅启动Apache HTTP客户端一次,因为它是线程安全的,您可以安全地重用它。 如果您使用Spring,那么将它作为Bean存储在Spring Context中应该是安全的。 请参阅以下链接以获取线程安全性: http : //hc.apache.org/httpclient-3.x/performance.html 尽管HTTP客户端实例本身并未汇集(因为您将使用它的单个实例),但是为了提高性能,您可以在HTTP客户端上配置池连接管理器。 ...
  • 这只是一个不同的API。 Observable有更好的方法来分离“如何流动”(所有操作符:map,merge,concat等)与执行(.subscribe),这往往有助于获得更好的图片。 Plus提供有用的方法来取消或重试请求,如果失败。 如果你需要Promise API,你可以随时使用Observable.toPromise() (使用async / await,这也很有用) 所以对我来说,这只是表示同一事物的两种方式,每种方式都有其优势,但由于Observable更通用,他们使用了这种方法 - 可以将O ...