java設(shè)置HTTP請(qǐng)求header的多種實(shí)現(xiàn)方式詳解
在Java中,可以通過(guò)多種方式設(shè)置HTTP請(qǐng)求的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();
// 設(shè)置請(qǐng)求方法
connection.setRequestMethod("POST");
// 設(shè)置請(qǐng)求頭
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer token123");
connection.setRequestProperty("User-Agent", "MyApp/1.0");
connection.setRequestProperty("X-Custom-Header", "CustomValue");
// 設(shè)置連接超時(shí)
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 發(fā)送請(qǐng)求體(如果是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);
}
// 獲取響應(yīng)
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 讀取響應(yīng)
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");
// 設(shè)置請(qǐng)求頭
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization", "Bearer token123");
httpPost.setHeader("X-Custom-Header", "CustomValue");
httpPost.setHeader("User-Agent", "MyApp/1.0");
// 設(shè)置請(qǐng)求體
String json = "{\"key\": \"value\"}";
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// 執(zhí)行請(qǐng)求
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();
// 設(shè)置請(qǐng)求頭
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));
// 設(shè)置請(qǐng)求體
String requestBody = "{\"key\": \"value\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
// 發(fā)送請(qǐng)求
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)建請(qǐng)求體
MediaType mediaType = MediaType.parse("application/json");
String json = "{\"key\": \"value\"}";
RequestBody body = RequestBody.create(mediaType, json);
// 構(gòu)建請(qǐng)求
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ā)送請(qǐng)求
try (Response response = client.newCall(request).execute()) {
System.out.println("Code: " + response.code());
System.out.println("Response: " + response.body().string());
}
}
}5. 在Servlet中設(shè)置響應(yīng)頭
如果是在Servlet中處理HTTP請(qǐng)求,可以設(shè)置響應(yīng)頭:
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 {
// 設(shè)置響應(yīng)頭
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");
// 添加多個(gè)相同名稱的頭
response.addHeader("Set-Cookie", "token=abc123");
response.addHeader("Set-Cookie", "session=xyz789");
// 寫入響應(yīng)體
response.getWriter().write("{\"status\": \"success\"}");
}
}常用HTTP頭字段
| 頭字段 | 說(shuō)明 | 示例 |
|---|---|---|
| Content-Type | 請(qǐng)求/響應(yīng)體類型 | application/json |
| Authorization | 認(rèn)證信息 | Bearer token123 |
| User-Agent | 客戶端信息 | MyApp/1.0 |
| Accept | 可接受的響應(yīng)類型 | application/json |
| Cache-Control | 緩存控制 | no-cache |
| X-Requested-With | AJAX請(qǐng)求標(biāo)識(shí) | XMLHttpRequest |
注意事項(xiàng)
- Content-Type:發(fā)送JSON數(shù)據(jù)時(shí)通常設(shè)置為
application/json - Authorization:用于身份驗(yàn)證,常見格式是
Bearer token - 自定義頭部:通常以
X-開頭,但不是強(qiáng)制要求 - 字符編碼:確保字符編碼正確,建議使用UTF-8
- 敏感信息:避免在URL中傳遞敏感信息,應(yīng)放在請(qǐng)求頭中
選擇哪種方式取決于你的項(xiàng)目需求:
- 簡(jiǎn)單項(xiàng)目:使用
HttpURLConnection - 需要更多功能:使用 Apache HttpClient 或 OkHttp
- Spring項(xiàng)目:使用 RestTemplate
- Servlet項(xiàng)目:直接使用
HttpServletResponse
到此這篇關(guān)于java設(shè)置HTTP請(qǐng)求header的多種實(shí)現(xiàn)方式詳解的文章就介紹到這了,更多相關(guān)java設(shè)置HTTP請(qǐng)求header內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中的定時(shí)任務(wù)調(diào)度Quartz舉例詳解
這篇文章主要介紹了Java中的定時(shí)任務(wù)調(diào)度Quartz的相關(guān)資料,Quartz是Java平臺(tái)上的一個(gè)強(qiáng)大且靈活的任務(wù)調(diào)度庫(kù),廣泛應(yīng)用于企業(yè)級(jí)應(yīng)用中,本文介紹了Quartz的基本概念、核心組件、使用步驟和示例,幫助你更好地利用Quartz進(jìn)行定時(shí)任務(wù)調(diào)度,需要的朋友可以參考下2024-12-12
SpringBoot測(cè)試配置屬性與web啟動(dòng)環(huán)境超詳細(xì)圖解
Web開發(fā)的核心內(nèi)容主要包括內(nèi)嵌的Servlet容器和SpringMVCSpringBoot使用起來(lái)非常簡(jiǎn)潔,大部分配置都有SpringBoot自動(dòng)裝配,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-10-10
SpringBoot統(tǒng)一api返回風(fēng)格的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot統(tǒng)一api返回風(fēng)格的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
解決Mybatis?plus實(shí)體類屬性與表字段不一致的問(wèn)題
這篇文章主要介紹了Mybatis?plus實(shí)體類屬性與表字段不一致解決方法,文末給大家提到了Mybatis-plus中數(shù)據(jù)庫(kù)表名和表字段名的相關(guān)知識(shí),需要的朋友可以參考下2022-07-07
JDBC實(shí)現(xiàn)學(xué)生管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了JDBC實(shí)現(xiàn)學(xué)生管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02

