使用Java发送POST请求的四种方式
作者:上班想摸鱼
这篇文章主要介绍了四种使用Java发送POST请求的方法,包括原生HttpURLConnection、Apache HttpClient、SpringRestTemplate以及Java11+的HttpClient,每种方法都提供了相应的Maven依赖和注意事项,需要的朋友可以参考下
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 {
// 请求URL
String url = "https://example.com/api";
// 创建连接
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("POST");
// 设置请求头
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
// 请求体数据
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 启用输出流
con.setDoOutput(true);
// 发送请求体
try(OutputStream os = con.getOutputStream()) {
byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应码
int responseCode = con.getResponseCode();
System.out.println("Response Code: " + responseCode);
// 读取响应
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()) {
// 创建POST请求
HttpPost httpPost = new HttpPost("https://example.com/api");
// 设置请求头
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
// 设置请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
httpPost.setEntity(new StringEntity(requestBody));
// 执行请求
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
// 获取响应码
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("Response Code: " + statusCode);
// 获取响应体
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) {
// 创建RestTemplate实例
RestTemplate restTemplate = new RestTemplate();
// 请求URL
String url = "https://example.com/api";
// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
// 请求体数据
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 创建请求实体
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
// 发送POST请求
ResponseEntity<String> response = restTemplate.postForEntity(url, requestEntity, String.class);
// 获取响应信息
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) {
// 创建HttpClient
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.connectTimeout(Duration.ofSeconds(10))
.build();
// 请求体
String requestBody = "{\"key1\":\"value1\",\"key2\":\"value2\"}";
// 创建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 {
// 发送请求
HttpResponse<String> response = httpClient.send(
request, HttpResponse.BodyHandlers.ofString());
// 输出结果
System.out.println("Status Code: " + response.statusCode());
System.out.println("Response Body: " + response.body());
} catch (Exception e) {
e.printStackTrace();
}
}
}注意事项
- 对于生产环境,推荐使用 Apache HttpClient 或 Spring RestTemplate
- 记得处理异常和关闭资源
- 根据实际需求设置适当的超时时间
- 对于 HTTPS 请求,可能需要配置 SSL 上下文
- 考虑使用连接池提高性能
以上方法都可以根据实际需求进行调整,例如添加认证头、处理不同的响应类型等。
以上就是使用Java发送POST请求的四种方式的详细内容,更多关于Java发送POST请求的资料请关注脚本之家其它相关文章!
