在Java开发中,如果需要发起简单的HTTP请求,不需要引入第三方HTTP客户端依赖,使用JDK自带的HttpURLConnection就能完成基础操作。它是URLConnection的子类,专门用于HTTP协议的连接处理,支持GET、POST等常见请求方法,适合轻量级的接口调用场景。

HttpURLConnection核心使用步骤
使用HttpURLConnection发起请求的整体流程比较固定,主要包含以下几个步骤:
- 创建URL对象,指定请求的目标地址
- 通过URL对象打开连接,转换为HttpURLConnection实例
- 设置请求方法、超时时间、请求头等相关参数
- 如果是POST请求,需要设置允许输出参数,并写入请求体
- 获取响应状态码,判断请求是否成功
- 读取响应内容,处理返回数据
- 最后关闭连接,释放资源
发起GET请求示例
GET请求是最常用的HTTP请求方法,参数一般拼接在URL后面,不需要请求体。下面是完整的GET请求实现代码:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpGetDemo {
public static void main(String[] args) {
// 目标请求地址,可替换为实际接口地址
String requestUrl = "http://ipipp.com/api/testGet?id=1&name=test";
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
// 创建URL对象
URL url = new URL(requestUrl);
// 打开连接并转换为HttpURLConnection
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 设置连接超时时间为5秒
connection.setConnectTimeout(5000);
// 设置读取超时时间为5秒
connection.setReadTimeout(5000);
// 设置通用的请求头
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 获取响应状态码
int responseCode = connection.getResponseCode();
System.out.println("响应状态码:" + responseCode);
// 判断请求是否成功,200表示成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 获取输入流
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
// 逐行读取响应内容
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println("响应内容:" + response.toString());
} else {
System.out.println("请求失败,状态码:" + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭资源
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
}
}
发起POST请求示例
POST请求的参数一般放在请求体中,需要设置允许输出内容,同时要注意请求头的Content-Type设置,下面是表单形式参数的POST请求示例:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpPostDemo {
public static void main(String[] args) {
// 目标请求地址
String requestUrl = "http://ipipp.com/api/testPost";
// POST请求参数,表单格式
String postParams = "id=1&name=test&age=20";
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(requestUrl);
connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为POST
connection.setRequestMethod("POST");
// 设置连接和读取超时时间
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
// 设置请求头,表单格式参数
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
// 允许向连接输出内容,POST请求必须设置
connection.setDoOutput(true);
// 获取输出流,写入请求参数
OutputStream outputStream = connection.getOutputStream();
outputStream.write(postParams.getBytes("UTF-8"));
outputStream.flush();
outputStream.close();
// 获取响应状态码
int responseCode = connection.getResponseCode();
System.out.println("响应状态码:" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println("响应内容:" + response.toString());
} else {
System.out.println("请求失败,状态码:" + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
if (connection != null) {
connection.disconnect();
}
}
}
}
注意事项
在使用HttpURLConnection时,有几个常见的注意点需要关注:
- 如果请求的是HTTPS地址,可能需要处理证书验证问题,默认情况下JDK会验证证书,测试环境可以暂时跳过验证,但生产环境不建议这么做
- 读取响应内容时,如果响应是错误状态码,需要通过
connection.getErrorStream()获取错误流的返回内容,而不是getInputStream() - 设置请求参数时,如果有中文内容,需要提前进行URL编码,避免出现乱码问题
- 连接使用完成后一定要调用
disconnect()方法关闭,或者把相关流正确关闭,避免资源泄露 - HttpURLConnection默认是长连接,如果需要短连接,可以设置请求头
Connection为close
常见问题说明
很多开发者会遇到请求返回乱码的问题,一般是因为读取响应时的字符集和服务器返回的字符集不一致导致的。可以在读取前先获取响应头的Content-Type,从中提取字符集,如果没有指定,默认使用UTF-8。另外,POST请求如果是JSON格式参数,需要把Content-Type设置为application/json,同时把参数转换为JSON字符串再写入输出流。
如果是需要传递文件或者复杂的请求体,HttpURLConnection也支持,只需要设置对应的Content-Type,按照格式拼接请求体内容即可,不过对于复杂的HTTP场景,更推荐使用Apache HttpClient或者OkHttp等成熟的第三方客户端,功能更完善,使用也更方便。
JavaHttpURLConnectionHTTP请求URLConnection修改时间:2026-06-09 10:18:32