在Java中提交协议头(HTTP Headers)是开发网络应用时的常见需求,无论是调用RESTful API、爬虫数据还是实现微服务间通信,都离不开对请求头的灵活控制,本文将从基础到进阶,详细介绍Java中提交协议头的多种方法,涵盖标准库与第三方框架的使用场景,并提供实用代码示例。

使用HttpURLConnection提交协议头
Java标准库中的HttpURLConnection是处理HTTP请求的基础类,无需额外依赖即可实现协议头提交,其核心是通过setRequestProperty()方法设置请求头,适用于简单的HTTP请求场景。
基本步骤
- 创建URL对象:通过
new URL(url)初始化目标地址。 - 打开连接:调用
openConnection()获取HttpURLConnection实例。 - 设置请求方法:默认为GET,可通过
setRequestMethod("POST")等方法修改。 - 添加协议头:使用
setRequestProperty("Header-Name", "Header-Value")逐个添加。 - 发送请求并处理响应:通过
getInputStream()获取响应流。
示例代码
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class HttpURLConnectionExample {
public static void main(String[] args) throws Exception {
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("POST");
// 添加协议头
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer your_token");
connection.setRequestProperty("User-Agent", "Java-Client/1.0");
// 启用输出流(用于POST请求体)
connection.setDoOutput(true);
// 发送请求体(可选)
String jsonInput = "{\"key\":\"value\"}";
try (var os = connection.getOutputStream()) {
os.write(jsonInput.getBytes());
os.flush();
}
// 读取响应
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
String line;
StringBuilder response = new StringBuilder();
while ((line = br.readLine()) != null) {
response.append(line);
}
System.out.println("Response: " + response.toString());
}
} else {
System.out.println("Request failed with code: " + responseCode);
}
}
}
使用HttpClient(Java 11+)
Java 11引入了标准化的HttpClient,提供了更现代的API支持HTTP/2、异步请求等高级特性,通过HttpRequest.Builder可以链式调用设置协议头。

核心特点
- 支持同步与异步请求
- 原生支持HTTP/2
- 更灵活的请求体处理
示例代码
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class HttpClientExample {
public static void main(String[] args) throws Exception {
HttpClient client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.example.com/data"))
.header("Content-Type", "application/json")
.header("Authorization", "Bearer your_token")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}"))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Response status: " + response.statusCode());
System.out.println("Response body: " + response.body());
}
}
使用第三方库:Apache HttpClient
Apache HttpClient是功能强大的开源HTTP客户端,提供了更丰富的协议头管理功能,如多值头、自定义头处理器等。
依赖配置(Maven)
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.3.1</version>
</dependency>
示例代码
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.io.entity.StringEntity;
public class ApacheHttpClientExample {
public static void main(String[] args) throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://api.example.com/data");
// 设置协议头
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer your_token");
httpPost.setHeader("Custom-Header", "custom_value");
// 设置请求体
String json = "{\"key\":\"value\"}";
httpPost.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
// 执行请求
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
System.out.println("Response status: " + response.getCode());
// 处理响应...
}
}
}
}
高级场景:动态协议头与拦截器
在实际开发中,可能需要动态修改协议头或统一处理认证逻辑,此时可通过拦截器(Interceptor)模式实现。

OkHttp拦截器示例
import okhttp3.*;
import java.io.IOException;
public class OkHttpInterceptorExample {
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
Request requestWithHeaders = originalRequest.newBuilder()
.header("User-Agent", "OkHttp-App/1.0")
.header("X-Custom-Header", "intercepted")
.build();
return chain.proceed(requestWithHeaders);
}
})
.build();
Request request = new Request.Builder()
.url("https://api.example.com/data")
.header("Authorization", "Bearer your_token")
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println("Response: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}
注意事项
- 编码规范:协议头名称不区分大小写,但值可能区分,需遵循API文档规范。
- 安全性:敏感信息(如Token)应通过HTTPS传输,避免在日志中泄露。
- 性能优化:对于高频请求,复用HttpClient实例(如OkHttp的连接池)可提升性能。
- 异常处理:网络请求需处理超时、重试等异常场景,确保程序健壮性。
通过以上方法,开发者可以根据项目需求选择合适的技术方案灵活管理HTTP协议头,无论是简单的工具调用还是复杂的分布式系统,都能找到适配的实现方式。

















