package com.srs.common.utils;
import com.alibaba.fastjson2.JSON;
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.HttpClients;
import org.apache.http.util.EntityUtils;


import java.nio.charset.StandardCharsets;
import java.util.Map;

public class HttpJsonUtil {
    public static String postJson(String url, Map<String, Object> body, Map<String, String> headers) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpPost post = new HttpPost(url);
            // headers
            for (Map.Entry<String, String> h : headers.entrySet()) {
                post.setHeader(h.getKey(), h.getValue());
            }
            // body
            StringEntity entity = new StringEntity(JSON.toJSONString(body), StandardCharsets.UTF_8);
            post.setEntity(entity);
            try (CloseableHttpResponse resp = client.execute(post)) {
                int status = resp.getStatusLine().getStatusCode();
                String respStr = EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
                if (status == 200) {
                    return respStr;
                } else {
                    throw new RuntimeException("Coze 请求失败, status=" + status + ", resp=" + respStr);
                }
            }
        }
    }
}
