news 2026/7/8 13:59:42

java HttpServletRequest 设置header

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
java HttpServletRequest 设置header

在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

注意事项

  1. Content-Type:发送JSON数据时通常设置为application/json

  2. Authorization:用于身份验证,常见格式是Bearer token

  3. 自定义头部:通常以X-开头,但不是强制要求

  4. 字符编码:确保字符编码正确,建议使用UTF-8

  5. 敏感信息:避免在URL中传递敏感信息,应放在请求头中

选择哪种方式取决于你的项目需求:

  • 简单项目:使用HttpURLConnection

  • 需要更多功能:使用 Apache HttpClient 或 OkHttp

  • Spring项目:使用 RestTemplate

  • Servlet项目:直接使用HttpServletResponse

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/25 19:42:20

Windows HEIC缩略图终极方案:5分钟解决苹果照片预览难题

Windows HEIC缩略图终极方案&#xff1a;5分钟解决苹果照片预览难题 【免费下载链接】windows-heic-thumbnails Enable Windows Explorer to display thumbnails for HEIC files 项目地址: https://gitcode.com/gh_mirrors/wi/windows-heic-thumbnails 还在为Windows系统…

作者头像 李华
网站建设 2026/7/3 19:39:06

OpenCore图形化配置工具:从零基础到专业配置的完整指南

OpenCore图形化配置工具&#xff1a;从零基础到专业配置的完整指南 【免费下载链接】OpenCore-Configurator A configurator for the OpenCore Bootloader 项目地址: https://gitcode.com/gh_mirrors/op/OpenCore-Configurator 还在为复杂的OpenCore引导配置而烦恼吗&am…

作者头像 李华
网站建设 2026/7/1 18:29:58

解锁M芯片Mac隐藏技能:用PlayCover畅玩iOS游戏的完整指南

解锁M芯片Mac隐藏技能&#xff1a;用PlayCover畅玩iOS游戏的完整指南 【免费下载链接】PlayCover Community fork of PlayCover 项目地址: https://gitcode.com/gh_mirrors/pl/PlayCover 还在为无法在Mac上体验手机游戏的乐趣而烦恼吗&#xff1f;PlayCover这款专为Appl…

作者头像 李华
网站建设 2026/6/29 22:28:29

5分钟精通:PowerPoint LaTeX公式排版完整指南

5分钟精通&#xff1a;PowerPoint LaTeX公式排版完整指南 【免费下载链接】latex-ppt Use LaTeX in PowerPoint 项目地址: https://gitcode.com/gh_mirrors/la/latex-ppt 还在为PowerPoint中数学公式排版效率低下而困扰吗&#xff1f;想要让学术报告、教学课件中的数学表…

作者头像 李华
网站建设 2026/6/26 10:15:37

OpenCore Legacy Patcher技术解析:突破苹果硬件限制的创新方案

在苹果生态系统中&#xff0c;硬件与软件的深度绑定往往意味着旧款设备的快速淘汰。然而&#xff0c;OpenCore Legacy Patcher的出现彻底改变了这一现状&#xff0c;为2007至2017年间发布的Intel架构Mac设备提供了运行最新macOS系统的可能性。这款开源工具通过创新的引导层技术…

作者头像 李华