news 2026/4/18 12:06:31

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/4/18 3:26:48

高效图片浏览新选择:ImageGlass免费轻量级查看器完全指南

高效图片浏览新选择&#xff1a;ImageGlass免费轻量级查看器完全指南 【免费下载链接】ImageGlass &#x1f3de; A lightweight, versatile image viewer 项目地址: https://gitcode.com/gh_mirrors/im/ImageGlass 还在为Windows系统自带的图片查看器功能单一、启动缓慢…

作者头像 李华
网站建设 2026/4/17 15:14:26

强烈安利9个AI论文平台,专科生轻松搞定毕业论文!

强烈安利9个AI论文平台&#xff0c;专科生轻松搞定毕业论文&#xff01; AI工具让论文写作不再难 在如今这个信息爆炸的时代&#xff0c;专科生面对毕业论文的压力越来越明显。无论是选题、写作还是降重&#xff0c;每一个环节都可能让人感到力不从心。而随着AI技术的不断进步&…

作者头像 李华
网站建设 2026/4/18 2:09:07

PlayCover深度解析:在Apple Silicon Mac上完美运行iOS应用

PlayCover深度解析&#xff1a;在Apple Silicon Mac上完美运行iOS应用 【免费下载链接】PlayCover Community fork of PlayCover 项目地址: https://gitcode.com/gh_mirrors/pl/PlayCover 想让你手中的Apple Silicon Mac变身成为iOS应用平台吗&#xff1f;PlayCover这款…

作者头像 李华
网站建设 2026/4/17 13:08:37

SD-PPP:重新定义Photoshop中的AI创作工作流

在当今AI技术蓬勃发展的时代&#xff0c;设计师们面临着前所未有的创作机遇与挑战。SD-PPP作为一款创新的Photoshop插件&#xff0c;彻底改变了传统AI绘图与专业设计软件之间的协作模式。通过将ComfyUI的强大AI能力无缝集成到Photoshop工作环境中&#xff0c;SD-PPP让创意实现变…

作者头像 李华
网站建设 2026/4/17 12:58:24

WinBtrfs完整指南:在Windows系统上部署Linux原生文件系统

WinBtrfs完整指南&#xff1a;在Windows系统上部署Linux原生文件系统 【免费下载链接】btrfs WinBtrfs - an open-source btrfs driver for Windows 项目地址: https://gitcode.com/gh_mirrors/bt/btrfs 对于需要在Windows环境中访问Linux存储设备的用户来说&#xff0c…

作者头像 李华
网站建设 2026/4/17 23:50:02

华为光猫配置解密工具完整使用指南:快速掌握网络运维核心技术

网络运维工作中是否经常遇到华为光猫配置无法查看的困扰&#xff1f;配置参数调整缺乏有效依据&#xff1f;今天我们将全面解析这款专业级华为光猫配置解密工具&#xff0c;帮助您彻底解决网络运维中的配置管理难题。 【免费下载链接】HuaWei-Optical-Network-Terminal-Decoder…

作者头像 李华