在Java中,可以通过多种方式设置HTTP请求的header,具体取决于你使用的是哪种HTTP客户端。以下是几种常见的方法:
1. 使用原生 HttpURLConnection
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
public class HttpURLConnectionExample {
public static void main(String[] args) throws Exception {
URL url = new URL("http://example.com/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("POST");
// 设置请求头
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer token123");
connection.setRequestProperty("User-Agent", "MyApp/1.0");
connection.setRequestProperty("X-Custom-Header", "CustomValue");
// 设置连接超时
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 发送请求体(如果是POST/PUT)
connection.setDoOutput(true);
String jsonInput = "{\"key\": \"value\"}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInput.getBytes("utf-8");
os.write(input, 0, input.length);
}
// 获取响应
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应
try (BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), "utf-8"))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response: " + response.toString());
}
connection.disconnect();
}
}
2. 使用 Apache HttpClient
首先添加依赖:
<!-- Maven -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;
public class ApacheHttpClientExample {
public static void main(String[] args) throws Exception {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("http://example.com/api");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer token123");
httpPost.setHeader("X-Custom-Header", "CustomValue");
httpPost.setHeader("User-Agent", "MyApp/1.0");
// 设置请求体
String json = "{\"key\": \"value\"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// 执行请求
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
System.out.println("Status: " + response.getStatusLine());
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Response: " + responseBody);
}
}
}
}
3. 使用 Spring RestTemplate
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.Collections;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer token123");
headers.set("X-Custom-Header", "CustomValue");
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// 设置请求体
String requestBody = "{\"key\": \"value\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
// 发送请求
ResponseEntity<String> response = restTemplate.exchange(
"http://example.com/api",
HttpMethod.POST,
requestEntity,
String.class
);
System.out.println("Status: " + response.getStatusCode());
System.out.println("Response: " + response.getBody());
}
}
4. 使用 OkHttp
首先添加依赖:
<!-- Maven -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.9.3</version>
</dependency>
import okhttp3.*;
public class OkHttpExample {
public static void main(String[] args) throws Exception {
OkHttpClient client = new OkHttpClient();
// 创建请求体
MediaType mediaType = MediaType.parse("application/json");
String json = "{\"key\": \"value\"}";
RequestBody body = RequestBody.create(mediaType, json);
// 构建请求
Request request = new Request.Builder()
.url("http://example.com/api")
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Bearer token123")
.addHeader("X-Custom-Header", "CustomValue")
.addHeader("User-Agent", "MyApp/1.0")
.build();
// 发送请求
try (Response response = client.newCall(request).execute()) {
System.out.println("Code: " + response.code());
System.out.println("Response: " + response.body().string());
}
}
}
5. 在Servlet中设置响应头
如果是在Servlet中处理HTTP请求,可以设置响应头:
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/api")
public class MyServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException {
// 设置响应头
response.setHeader("Content-Type", "application/json");
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "0");
response.setHeader("X-Custom-Header", "CustomValue");
// 或者使用setHeader的便捷方法
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
// 添加多个相同名称的头
response.addHeader("Set-Cookie", "token=abc123");
response.addHeader("Set-Cookie", "session=xyz789");
// 写入响应体
response.getWriter().write("{\"status\": \"success\"}");
}
}
常用HTTP头字段
| 头字段 | 说明 | 示例 |
|---|---|---|
| Content-Type | 请求/响应体类型 | application/json |
| Authorization | 认证信息 | Bearer token123 |
| User-Agent | 客户端信息 | MyApp/1.0 |
| Accept | 可接受的响应类型 | application/json |
| Cache-Control | 缓存控制 | no-cache |
| X-Requested-With | AJAX请求标识 | XMLHttpRequest |
注意事项
-
Content-Type :发送JSON数据时通常设置为
application/json -
Authorization :用于身份验证,常见格式是
Bearer token -
自定义头部 :通常以
X-开头,但不是强制要求 -
字符编码:确保字符编码正确,建议使用UTF-8
-
敏感信息:避免在URL中传递敏感信息,应放在请求头中
选择哪种方式取决于你的项目需求:
-
简单项目:使用
HttpURLConnection -
需要更多功能:使用 Apache HttpClient 或 OkHttp
-
Spring项目:使用 RestTemplate
-
Servlet项目:直接使用
HttpServletResponse