java設置HTTP請求header的多種實現(xiàn)方式詳解
在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);
// 發(fā)送請求體(如果是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);
// 執(zhí)行請求
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);
// 發(fā)送請求
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();
// 創(chuàng)建請求體
MediaType mediaType = MediaType.parse("application/json");
String json = "{\"key\": \"value\"}";
RequestBody body = RequestBody.create(mediaType, json);
// 構(gòu)建請求
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();
// 發(fā)送請求
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:發(fā)送JSON數(shù)據(jù)時通常設置為
application/json - Authorization:用于身份驗證,常見格式是
Bearer token - 自定義頭部:通常以
X-開頭,但不是強制要求 - 字符編碼:確保字符編碼正確,建議使用UTF-8
- 敏感信息:避免在URL中傳遞敏感信息,應放在請求頭中
選擇哪種方式取決于你的項目需求:
- 簡單項目:使用
HttpURLConnection - 需要更多功能:使用 Apache HttpClient 或 OkHttp
- Spring項目:使用 RestTemplate
- Servlet項目:直接使用
HttpServletResponse
到此這篇關(guān)于java設置HTTP請求header的多種實現(xiàn)方式詳解的文章就介紹到這了,更多相關(guān)java設置HTTP請求header內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
一篇文章徹底弄懂SpringBoot項目jdk版本及依賴不兼容問題
這篇文章主要給大家介紹了關(guān)于徹底弄懂SpringBoot項目jdk版本及依賴不兼容問題的相關(guān)資料,文中通過圖文介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2023-01-01
MyBatis?原生二級緩存"難以修復"的原因解析及解決方案
文章主要討論了MyBatis原生二級緩存存在的問題,包括結(jié)構(gòu)性缺陷、難以修復等,社區(qū)提供了多種增強插件方案,但這些方案也有各自的優(yōu)缺點,本文結(jié)合實例代碼介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧2025-12-12
spring通過filter,Interceptor統(tǒng)一處理ResponseBody的返回值操作
這篇文章主要介紹了spring通過filter,Interceptor統(tǒng)一處理ResponseBody的返回值操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
SpringBoot基于Redis實現(xiàn)token的在線續(xù)期的實踐
本文主要介紹了使用Redis實現(xiàn)JWT令牌在線續(xù)期的方案,通過在線續(xù)期token,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-12-12
如何解決UnsupportedOperationException異常問題
這篇文章主要介紹了如何解決UnsupportedOperationException異常問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
Linux中Java開發(fā)常用軟件安裝方法總結(jié)
這篇文章主要介紹了Linux中Java開發(fā)常用軟件安裝方法總結(jié),需要的朋友可以參考下2020-02-02

