本文目录导读:

- 使用 HttpURLConnection(原生方式)
- 使用 Apache HttpClient
- 使用 OkHttp
- 使用 Spring RestTemplate(Spring 框架)
- 使用 Java 11+ HttpClient(内置)
- 总结与建议
在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 HttpURLConnectionExample {
// GET请求
public static String sendGet(String urlStr) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("响应码: " + responseCode);
// 读取响应
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
// POST请求
public static String sendPost(String urlStr, String jsonBody) throws Exception {
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 写入请求体
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonBody.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应
int responseCode = connection.getResponseCode();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
return response.toString();
}
public static void main(String[] args) {
try {
// GET请求示例
String getResponse = sendGet("http://jsonplaceholder.typicode.com/posts/1");
System.out.println("GET响应: " + getResponse);
// POST请求示例
String jsonBody = "{\"title\": \"foo\", \"body\": \"bar\", \"userId\": 1}";
String postResponse = sendPost("http://jsonplaceholder.typicode.com/posts", jsonBody);
System.out.println("POST响应: " + postResponse);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 Apache HttpClient
首先添加 Maven 依赖:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.14</version>
</dependency>
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
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 HttpClientExample {
// GET请求
public static String sendGet(String url) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpGet request = new HttpGet(url);
request.setHeader("Content-Type", "application/json");
HttpResponse response = client.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("响应码: " + statusCode);
return EntityUtils.toString(response.getEntity());
}
}
// POST请求
public static String sendPost(String url, String jsonBody) throws Exception {
try (CloseableHttpClient client = HttpClients.createDefault()) {
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/json");
request.setEntity(new StringEntity(jsonBody, "UTF-8"));
HttpResponse response = client.execute(request);
return EntityUtils.toString(response.getEntity());
}
}
public static void main(String[] args) {
try {
String response = sendGet("http://jsonplaceholder.typicode.com/posts/1");
System.out.println("响应: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 OkHttp
添加 Maven 依赖:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.12.0</version>
</dependency>
import okhttp3.*;
import java.io.IOException;
public class OkHttpExample {
private static final OkHttpClient client = new OkHttpClient();
// GET请求
public static String sendGet(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.addHeader("Content-Type", "application/json")
.build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("请求失败: " + response.code());
}
return response.body().string();
}
}
// POST请求
public static String sendPost(String url, String jsonBody) throws IOException {
MediaType JSON = MediaType.get("application/json; charset=utf-8");
RequestBody body = RequestBody.create(jsonBody, JSON);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
// 异步请求
public static void sendAsyncGet(String url) {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
System.out.println("异步响应: " + response.body().string());
}
});
}
public static void main(String[] args) {
try {
String response = sendGet("http://jsonplaceholder.typicode.com/posts/1");
System.out.println("响应: " + response);
// 异步请求
sendAsyncGet("http://jsonplaceholder.typicode.com/posts/1");
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 Spring RestTemplate(Spring 框架)
添加 Maven 依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static String sendGet(String url) {
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
return response.getBody();
}
public static String sendPost(String url, String jsonBody) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> request = new HttpEntity<>(jsonBody, headers);
ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
return response.getBody();
}
public static void main(String[] args) {
String response = sendGet("http://jsonplaceholder.typicode.com/posts/1");
System.out.println("响应: " + response);
}
}
使用 Java 11+ HttpClient(内置)
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 JavaHttpClientExample {
private static final HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
// GET请求
public static String sendGet(String url) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(5))
.GET()
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return response.body();
}
// POST请求
public static String sendPost(String url, String jsonBody) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json")
.timeout(Duration.ofSeconds(5))
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.build();
HttpResponse<String> response = client.send(request,
HttpResponse.BodyHandlers.ofString());
return response.body();
}
public static void main(String[] args) {
try {
String response = sendGet("http://jsonplaceholder.typicode.com/posts/1");
System.out.println("响应: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
总结与建议
| 方式 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| HttpURLConnection | 无需第三方依赖 | API较原始,代码量多 | 简单请求 |
| Apache HttpClient | 功能完善,稳定性高 | 需要引入依赖 | 企业级应用 |
| OkHttp | 性能优秀,支持HTTP/2 | 需要引入依赖 | 移动端/高性能场景 |
| Spring RestTemplate | 与Spring集成好 | 依赖Spring框架 | Spring项目 |
| Java HttpClient(11+) | 内置,API现代化 | 仅支持Java11+ | Java11+项目 |
建议:
- 如果使用Spring Boot,优先选择 RestTemplate 或 WebClient
- 新项目推荐使用 OkHttp 或 Java 11+ HttpClient
- 简单的测试场景可以使用 HttpURLConnection