package nc.bs.uapbd.util;


import nc.vo.pub.BusinessException;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
 * @Classname ThirdPartyPostRequestUtil
 * @Description TODO
 * @Version 1.0.0
 * @Date 2025/5/15 18:22
 * @Created by ame
 */
public class ThirdPartyPostRequestUtil {

    private static final int DEFAULT_CONNECT_TIMEOUT = 300000;
    private static final int DEFAULT_READ_TIMEOUT = 300000;

    /**
     * 向第三方系统发送 POST 请求，并根据 HTTP 状态码返回数据
     *
     * @param requestUrl  请求地址
     * @param requestBody 请求体（JSON 格式）
     * @return 如果响应码为 200，则返回响应内容；否则返回错误信息
     */
    public static String sendPostRequest(String requestUrl, String requestBody) throws BusinessException {
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法和参数
            connection.setRequestMethod("POST");
            connection.setDoOutput(true); // 允许输出
            connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT); // 设置连接超时时间
            connection.setReadTimeout(DEFAULT_READ_TIMEOUT); // 设置读取超时时间
            connection.setRequestProperty("Content-Type", "application/json"); // 设置请求头

            // 发送请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes("utf-8");
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String line;
                StringBuilder responseBuilder = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    responseBuilder.append(line);
                }
                in.close();
                return responseBuilder.toString(); // 返回成功响应数据
            } else {
                throw new BusinessException("POST 请求失败，响应码：" + responseCode) ; // 返回失败信息
            }
        } catch (Exception e) {
            throw new BusinessException("发生异常：" + e.getMessage()) ; // 异常处理
        }
    }

}
