package fi.rim.utils;


import com.alibaba.fastjson.JSON;
import kd.bos.script.annotations.KSObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
@KSObject
public class ApiHttpUtils {

    public static String Posthttp(String url, String Params) throws Exception {
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建Post请求
        //设置请求路径
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        StringEntity entity = new StringEntity(Params,"UTF-8");
        // post请求是将参数放在请求体里面传过去的;这里将entity放入post请求体中
        // 设置编码格式
        entity.setContentEncoding("UTF-8");
        // 发送Json格式的数据请求
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        // 响应模型(发送post请求)
        CloseableHttpResponse response = httpClient.execute(httpPost);
        // 从响应模型中获取响应实体
        HttpEntity responseEntity = response.getEntity();
        com.alibaba.fastjson.JSONObject jsonObject = new com.alibaba.fastjson.JSONObject();
        if (responseEntity != null) {
            jsonObject = JSON.parseObject(EntityUtils.toString(response.getEntity()));
            return jsonObject.toJSONString();
        }
        // 释放资源
        if (httpClient != null) {
            httpClient.close();
        }
        if (response != null) {
            response.close();
        }
        return "";
    }
}