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

相关推荐
Chester_19995 小时前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
EXI-小洲6 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
会周易的程序员6 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导6 小时前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan6 小时前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_695251497 小时前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
2601_961901707 小时前
SpringBoot使用Nacos进行application.yml配置管理
java·spring boot·spring
何以解忧,唯有..8 小时前
LangChain 工具调用(Tool Calling)实战指南
java·前端·langchain
大衛說8 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
QQ_21696290968 小时前
【源码编号:project79475】SpringBoot校内二手交易平台:商品发布、分类检索、留言交流、订单管理全流程实战
java·spring boot·后端