HttpUtil.java 2.71 KB
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(); // 关闭连接
            }
        }
    }
}