本文目录导读:

我来详细介绍使用 URLConnection 发送 HTTP 请求的方法。
基本 GET 请求
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetExample {
public static void main(String[] args) {
try {
// 创建 URL 对象
URL url = new URL("https://api.example.com/users");
// 打开连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法
connection.setRequestMethod("GET");
// 设置请求头
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept", "application/json");
// 设置超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 获取响应码
int responseCode = connection.getResponseCode();
System.out.println("响应码: " + responseCode);
// 读取响应
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("响应内容: " + response.toString());
} else {
System.out.println("请求失败");
}
// 断开连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
POST 请求(带参数)
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class HttpPostExample {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/users");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置 POST 请求
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置请求头
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Charset", "UTF-8");
// 构建请求参数
String urlParameters = "username=" + URLEncoder.encode("张三", "UTF-8")
+ "&password=" + URLEncoder.encode("123456", "UTF-8")
+ "&age=" + URLEncoder.encode("25", "UTF-8");
// 发送 POST 参数
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
// 获取响应
int responseCode = connection.getResponseCode();
BufferedReader in = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String inputLine;
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("响应码: " + responseCode);
System.out.println("响应内容: " + response.toString());
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
JSON 格式的 POST 请求
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostJsonExample {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/users");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求头
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
// 构建 JSON 数据
String jsonInputString = "{\"name\": \"张三\", \"age\": 25, \"email\": \"zhangsan@example.com\"}";
// 发送 JSON 数据
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
byte[] input = jsonInputString.getBytes("utf-8");
wr.write(input, 0, input.length);
}
// 读取响应
int responseCode = connection.getResponseCode();
// 根据响应码选择输入流
BufferedReader in;
if (responseCode >= 200 && responseCode < 300) {
in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
StringBuilder response = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
System.out.println("响应码: " + responseCode);
System.out.println("响应内容: " + response.toString());
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
PUT 请求(更新数据)
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPutExample {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/users/123");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置 PUT 请求
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
// 要更新的数据
String updateData = "{\"name\": \"李四\", \"age\": 30}";
// 发送数据
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
byte[] input = updateData.getBytes("utf-8");
wr.write(input, 0, input.length);
}
int responseCode = connection.getResponseCode();
System.out.println("响应码: " + responseCode);
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
DELETE 请求
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpDeleteExample {
public static void main(String[] args) {
try {
URL url = new URL("https://api.example.com/users/123");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置 DELETE 请求
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
if (responseCode == 200 || responseCode == 204) {
System.out.println("删除成功");
} else {
System.out.println("删除失败,响应码: " + responseCode);
}
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}
带超时和自动重定向的封装类
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
public class HttpClientUtil {
private static final int CONNECT_TIMEOUT = 5000;
private static final int READ_TIMEOUT = 5000;
/**
* 发送 GET 请求
*/
public static String doGet(String url, Map<String, String> headers) throws Exception {
HttpURLConnection connection = null;
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
// 设置基础属性
connection.setRequestMethod("GET");
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setInstanceFollowRedirects(true); // 自动重定向
// 设置请求头
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 获取响应
return getResponse(connection);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* 发送 POST 请求
*/
public static String doPost(String url, String data, String contentType,
Map<String, String> headers) throws Exception {
HttpURLConnection connection = null;
try {
URL requestUrl = new URL(url);
connection = (HttpURLConnection) requestUrl.openConnection();
// 设置基础属性
connection.setRequestMethod("POST");
connection.setConnectTimeout(CONNECT_TIMEOUT);
connection.setReadTimeout(READ_TIMEOUT);
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置请求头
if (contentType != null) {
connection.setRequestProperty("Content-Type", contentType);
}
if (headers != null && !headers.isEmpty()) {
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
// 发送数据
if (data != null && !data.isEmpty()) {
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
byte[] input = data.getBytes("utf-8");
wr.write(input, 0, input.length);
}
}
// 获取响应
return getResponse(connection);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* 获取响应内容
*/
private static String getResponse(HttpURLConnection connection) throws IOException {
int responseCode = connection.getResponseCode();
// 根据响应码选择输入流
InputStream inputStream;
if (responseCode >= 200 && responseCode < 300) {
inputStream = connection.getInputStream();
} else {
inputStream = connection.getErrorStream();
}
// 读取响应
StringBuilder response = new StringBuilder();
if (inputStream != null) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"))) {
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
}
}
return response.toString();
}
// 使用示例
public static void main(String[] args) {
try {
// GET 请求
String getResult = doGet("https://api.example.com/data", null);
System.out.println("GET 结果: " + getResult);
// POST 请求
String jsonData = "{\"key\": \"value\"}";
String postResult = doPost("https://api.example.com/data",
jsonData,
"application/json",
null);
System.out.println("POST 结果: " + postResult);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意事项
- 设置超时时间:避免请求长时间挂起
- 处理字符编码:确保使用 UTF-8
- 关闭连接:使用完必须调用
disconnect() - 错误处理:检查响应码并处理错误流
- 安全性:不要在 URL 中传递敏感信息
代码覆盖了常见的 HTTP 请求场景,可以根据实际需求选择使用。