package com.xy.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xy.error.CommRuntimeException;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;

@Slf4j
public class HttpUtils {

    public static JSONObject send(String url, JSONObject params, String msg) {
        return request(url, params.toString(), msg, null);
    }

    public static JSONObject send(String url, JSONObject params, String msg, Map<String, String> headers) {
        return request(url, params.toString(), msg, headers);
    }

    public static JSONObject send(String url, String body, String msg) {
        return request(url, body, msg, null);
    }

    public static JSONObject send(String url, String body, String msg, Map<String, String> headers) {
        return request(url, body, msg, headers);
    }

    private static JSONObject request(String url, String body, String msg, Map<String, String> headers) {
        log.info("{}请求参数：{}", msg, body);
        String result = HttpRequest.post(url)
                .body(body)
                .addHeaders(headers)
                .timeout(5000)
                .execute()
                .body();
        log.info("{}响应参数：{}", msg, result);
        JSONObject jsonObject;
        try {
            jsonObject = JSONUtil.parseObj(result);
        } catch (Exception e) {
            throw new CommRuntimeException(msg + "失败");
        }
        return jsonObject;
    }

}
