package com.jiayue.insu.incloud.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: zhangchenglong
 * @createDate: 2023/6/28
 * @version: 1.0
 */
@Slf4j
@Component
public class HttpUtils {

    /**
     * @param url
     * @param param
     * @return
     */
    public JSONObject httpPost(String url, HashMap<String, String> param) {
        JSONObject result = new JSONObject();
        String response = "";
        String paramStr = "?";
        if (param != null) {
            for (Map.Entry<String, String> entry : param.entrySet()) {
                paramStr = paramStr + entry.getKey() + "=" + entry.getValue() + "&";
            }
            paramStr = paramStr.substring(0, paramStr.length() - 1);
        }
        url = url + paramStr;
        try {
            HttpRequest httpRequest = HttpRequest.post(url)
                    .header("Content-Type", "application/json");
            httpRequest.setGlobalTimeout(20000);
            response = httpRequest.execute().body();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(JSONUtil.isTypeJSON(response)){
            // 将返回结果转为jsonjnn 6 vb
            result = JSONUtil.parseObj(response);
        }else{
            log.error("返回结果不是json类型，{}",response);
        }

        return result;
    }

}
