HttpUtil.java
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.lhcredit.common.utils.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class HttpUtil {
/**
* 发送 HTTP GET 请求
* @param url 请求地址(含参数)
* @return 响应结果字符串(如 JSON)
*/
public static String doGet(String url) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
// 1. 创建URL对象(只需创建一次)
URL requestUrl = new URL(url);
// 2. 打开连接
connection = (HttpURLConnection) requestUrl.openConnection();
// 3. 设置请求方法为GET(注意:方法名必须大写)
connection.setRequestMethod("GET");
// 4. 配置User-Agent请求头(模拟浏览器)
connection.setRequestProperty(
"User-Agent",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
);
// 5. 配置超时参数(毫秒)
connection.setConnectTimeout(5000); // 连接超时:5秒
connection.setReadTimeout(10000); // 读取超时:10秒
// 6. 发送请求并获取响应状态
int responseCode = connection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
// 非 200 状态码(如 400、401),抛出异常或返回错误信息
throw new RuntimeException("HTTP 请求失败,状态码:" + responseCode);
}
// 7. 读取响应内容
InputStream inputStream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
return response.toString();
} catch (IOException e) {
// 处理异常(如网络错误、超时)
throw new RuntimeException("HTTP GET 请求失败:" + e.getMessage(), e);
} finally {
// 8. 释放资源
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect(); // 关闭连接
}
}
}
}