package com.youchain.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.compress.utils.IOUtils;

import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class HttpPostUtil {
    public static String sendPostReq(String api_url, String request){
        InputStream instr = null;
        String str = "";
        try {
            URL url = new URL(api_url);
            URLConnection urlCon = url.openConnection();
            urlCon.setConnectTimeout(3000);
            byte[] xmlData = request.getBytes();
            urlCon.setDoOutput(true);
            urlCon.setDoInput(true);
            urlCon.setUseCaches(false);
            urlCon.setRequestProperty("content-Type", "application/json");
            urlCon.setRequestProperty("charset", "UTF-8");
            urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
            DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
            printout.write(xmlData);
            printout.flush();
            printout.close();
            instr = urlCon.getInputStream();
            byte[] bis = IOUtils.toByteArray(instr);
            String ResponseString = new String(bis, "UTF-8");
            if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
                System.out.println("返回空");
            }
            str = ResponseString;
        }catch (Exception e){
            throw new Error(e.getMessage());
        }
        /*JSONObject jsonObject=new JSONObject();
        jsonObject.accumulate("code", "0");
        jsonObject.accumulate("message", "");
        jsonObject.accumulate("success", true);
        jsonObject.accumulate("data", "");
        str= JSONUtil.toJsonStr(jsonObject.toString());*/
        return str;
    }
}
