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"

}

}

好的,您可以使用 JavaHttpURLConnection 类来发送带有 header 和 JSON 参数的请求。以下是一个示例代码: ```java import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUrlConnectionExample { public static void main(String[] args) { try { URL url = new URL("http://example.com/api/endpoint"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为 POST connection.setRequestMethod("POST"); // 设置请求头部 connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); connection.setRequestProperty("Authorization", "Bearer your_token_here"); // 设置可写入请求数据 connection.setDoOutput(true); // 构建 JSON 请求数据 String jsonData = "{\"name\":\"John Smith\",\"email\":\"john.smith@example.com\"}"; // 写入请求数据 DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(jsonData); outputStream.flush(); outputStream.close(); // 获取响应数据 int responseCode = connection.getResponseCode(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = reader.readLine()) != null) { response.append(inputLine); } reader.close(); // 输出响应数据 System.out.println(response.toString()); } catch (Exception e) { e.printStackTrace(); } } } ``` 在上面的示例中,我们首先创建了一个 URL 对象,并使用它创建了一个 HttpURLConnection 对象。接下来,我们设置请求方法为 POST,并设置请求头部,包括 Content-Type、Accept 和 Authorization。然后,我们设置了可写入请求数据,并将 JSON 数据写入请求输出流。最后,我们获取响应数据并输出它。请注意,这只是一个示例代码,您需要将 URL、请求头部和 JSON 数据替换为您自己的数据。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值