package com.youchain.utils;

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 = null;
        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) {
            System.out.println("接口异常!");
            // throw new Error(e.getMessage());
        }
        return str;
    }
}
