package net.northking.cctp.testbug.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

public class HttpClientUtil {
    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);

    public static String doPost(String pathUrl, String data) {
        return doPost(pathUrl, data, null);
    }

    private static String doPost(String pathUrl, String data, String token) {

        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {

            URL url = new URL(pathUrl);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);


            conn.setRequestProperty("accept", "application/json, text/plain, */*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type", "application/json");

            conn.connect();

            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");

            out.write(data);
            out.flush();

            InputStream inputStream = conn.getInputStream();
            br = new BufferedReader(new InputStreamReader(inputStream));
            System.out.println(br.ready());
            String str = "";

            while ((str = br.readLine()) != null) {
                result += str;
            }
            inputStream.close();
            conn.disconnect();

        } catch (Exception e) {
            logger.error("",e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                logger.error("",e);
            }
        }
        return result;
    }
}
