java设置httpheaders_HttpClient 请求添加Header头部信息

HTTP消息可以包含许多描述消息属性的标头,例如内容长度,内容类型,授权等。 HttpClient提供了检索,添加,删除和枚举标头的方法。 在下面的教程中,我们将演示如何将自定义HTTP头添加到HttpClient和Http请求方法。

Maven依赖关系

我们使用maven来管理依赖关系,并使用Apache HttpClient 4.5版本。 将以下依赖项添加到您的项目中。

pom.xml 文件的内容如下
 

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

4.0.0

com.yiibai.httpclient.httmethods

http-get

1.0.0-SNAPSHOT

https://memorynotfound.com

httpclient - ${project.artifactId}

org.apache.httpcomponents

httpclient

4.5.2

maven-compiler-plugin

3.5.1

1.8

1.8

自定义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 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 responseHandler = response -> {
int status = response.getStatusLine().getStatusCode();

if (status >= 200 && status 

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"

}

}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在使用HttpClient时,我们可以通过addHeader()方法来添加信息。可以根据需要设置不同的头信息来满足特定的需求。通过该方法,我们可以设置默认标头或者在消息上添加自定义的HTTP请求标头。同时,我们可以使用getAllHeaders()方法来获取所有的请求信息,返回的是一个Header数组,我们可以通过循环遍历打印出来。举个例子,我们可以通过在HttpPost对象上调用addHeader()方法来添加Cookie和User-Agent的请求信息。然后,通过调用httpPost.getAllHeaders()方法来获取添加请求头的数组。最后,我们可以通过for循环打印出来。执行上面示例代码,我们可以得到添加的头信息的结果。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [java设置httpheaders_HttpClient 请求添加Header头部信息](https://blog.csdn.net/renxingzhadan/article/details/119000330)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [HttpClient4 - 设置请求头](https://blog.csdn.net/m0_53753920/article/details/125339825)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值