package com.youchain.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.youchain.exception.BadRequestException;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.http.HttpStatus;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpPostUtil {
    public static String sendPostReq(String api_url, String request) {
        System.out.println("接口任务下发:"+api_url+":"+request);
        InputStream instr = null;
        String str = "";
        try {
            URL url = new URL(api_url);
            HttpURLConnection  urlCon = (HttpURLConnection) 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();
            if (urlCon.getResponseCode() != HttpURLConnection.HTTP_OK
                    &&urlCon.getResponseCode() != HttpURLConnection.HTTP_CREATED
                    &&urlCon.getResponseCode() != HttpURLConnection.HTTP_ACCEPTED ) {
                instr = urlCon.getErrorStream();
            }
            else{
                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){
            /*JSONObject jsonObject=new JSONObject();
            jsonObject.put("code","0");
            jsonObject.put("message","");
            jsonObject.put("data","");
            jsonObject.put("success","true");
            str=jsonObject.toString();*/
            throw new BadRequestException(HttpStatus.NOT_IMPLEMENTED, "接口调用异常"+api_url+request);
        }
        System.out.println("接口任务返回:"+str);
        return str;
    }
}
