使用Java發(fā)送POST請(qǐng)求的四種方式
更新時(shí)間:2025年11月07日 10:39:39 作者:上班想摸魚
這篇文章主要介紹了四種使用Java發(fā)送POST請(qǐng)求的方法,包括原生HttpURLConnection、Apache HttpClient、SpringRestTemplate以及Java11+的HttpClient,每種方法都提供了相應(yīng)的Maven依賴和注意事項(xiàng),需要的朋友可以參考下
1 使用 Java 原生 HttpURLConnection
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class PostRequestExample {
public static void main(String[] args) {
try {
// 請(qǐng)求URL
String url = "https://example.com/api";
// 創(chuàng)建連接
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 設(shè)置請(qǐng)求方法
con.setRequestMethod("POST");
// 設(shè)置請(qǐng)求頭
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
// 請(qǐng)求體數(shù)據(jù)
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 啟用輸出流
con.setDoOutput(true);
// 發(fā)送請(qǐng)求體
try(OutputStream os = con.getOutputStream()) {
byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 獲取響應(yīng)碼
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 讀取響應(yīng)
try(BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
System.out.println("Response: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}2. 使用 Apache HttpClient (推薦)
首先添加 Maven 依賴:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
代碼示例:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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.util.EntityUtils;
public class HttpClientPostExample {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
// 創(chuàng)建POST請(qǐng)求
HttpPost httpPost = new HttpPost("https://example.com/api");
// 設(shè)置請(qǐng)求頭
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
// 設(shè)置請(qǐng)求體
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
httpPost.setEntity(new StringEntity(requestBody));
// 執(zhí)行請(qǐng)求
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 獲取響應(yīng)碼
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + statusCode);
// 獲取響應(yīng)體
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println("Response: " + result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}3. 使用 Spring RestTemplate
首先添加 Maven 依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.5.0</version>
</dependency>
代碼示例:
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class RestTemplatePostExample {
public static void main(String[] args) {
// 創(chuàng)建RestTemplate實(shí)例
RestTemplate restTemplate = new RestTemplate();
// 請(qǐng)求URL
String url = "https://example.com/api";
// 設(shè)置請(qǐng)求頭
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// 請(qǐng)求體數(shù)據(jù)
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 創(chuàng)建請(qǐng)求實(shí)體
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
// 發(fā)送POST請(qǐng)求
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
// 獲取響應(yīng)信息
System.out.println("Response Code: " + response.getStatusCodeValue());
System.out.println("Response Body: " + response.getBody());
}
}4. 使用 Java 11+ 的 HttpClient (Java 11及以上版本)
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
public class Java11HttpClientExample {
public static void main(String[] args) {
// 創(chuàng)建HttpClient
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build();
// 請(qǐng)求體
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 創(chuàng)建HttpRequest
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://example.com/api"))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
try {
// 發(fā)送請(qǐng)求
HttpResponse<String> response = httpClient.send(
request, HttpResponse.BodyHandlers.ofString());
// 輸出結(jié)果
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}注意事項(xiàng)
- 對(duì)于生產(chǎn)環(huán)境,推薦使用 Apache HttpClient 或 Spring RestTemplate
- 記得處理異常和關(guān)閉資源
- 根據(jù)實(shí)際需求設(shè)置適當(dāng)?shù)某瑫r(shí)時(shí)間
- 對(duì)于 HTTPS 請(qǐng)求,可能需要配置 SSL 上下文
- 考慮使用連接池提高性能
以上方法都可以根據(jù)實(shí)際需求進(jìn)行調(diào)整,例如添加認(rèn)證頭、處理不同的響應(yīng)類型等。
以上就是使用Java發(fā)送POST請(qǐng)求的四種方式的詳細(xì)內(nèi)容,更多關(guān)于Java發(fā)送POST請(qǐng)求的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring中AOP概念與兩種動(dòng)態(tài)代理模式原理詳解
AOP是面向切面編程的技術(shù),AOP基于IoC基礎(chǔ),是對(duì)OOP的有益補(bǔ)充,流行的AOP框架有Sping AOP、AspectJ,這篇文章主要給大家介紹了關(guān)于Spring中AOP概念與兩種動(dòng)態(tài)代理模式原理的相關(guān)資料,需要的朋友可以參考下2021-10-10
SpringCloud將Nacos作為配置中心實(shí)現(xiàn)流程詳解
這篇文章主要介紹了Springcloud中的Nacos Config服務(wù)配置,本文以用戶微服務(wù)為例,進(jìn)行統(tǒng)一的配置,結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10
詳解jdbc實(shí)現(xiàn)對(duì)CLOB和BLOB數(shù)據(jù)類型的操作
這篇文章主要介紹了詳解jdbc實(shí)現(xiàn)對(duì)CLOB和BLOB數(shù)據(jù)類型的操作的相關(guān)資料,這里實(shí)現(xiàn)寫入操作與讀寫操作,需要的朋友可以參考下2017-08-08

