package com.tuoheng.admin.service.third.dsp;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

@Slf4j
public class SendPost {

    /**
     * 处理post请求
     * @param urlStr 请求url
     * @param data 请求体数据
     * @param properties 请求头参数
     * @return
     */
    public static String doPost(String urlStr, JSONObject data, Map<String, String> properties){
        try {
            log.info("请求url={}", urlStr);
            log.info("请求体数据data={}", data.toJSONString());
            log.info("请求头参数properties={}", properties);
            URL url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            connection.setDoInput(true); // 设置可输入
            connection.setDoOutput(true); // 设置该连接是可以输出的
            //设置连接超时时间和读取超时时间
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(60000);
            //设置请求方式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            if(null != properties && !properties.isEmpty()){
                for (String key:properties.keySet()){
                    connection.setRequestProperty(key, properties.get(key));
                }
            }

            PrintWriter pw = new PrintWriter(new BufferedOutputStream(connection.getOutputStream()));
            pw.write(data.toJSONString());
            pw.flush();
            pw.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
            String line = null;
            StringBuilder result = new StringBuilder();
            while ((line = br.readLine()) != null) { // 读取数据
                result.append(line + "\n");
            }
            connection.disconnect();
            return result.toString();
        } catch (Exception e) {
            log.error("post请求失败");
            return "post请求失败！";
        }
    }

}
