package com.muzhi.dingtalk.test.http;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

public class HttpUtils {

    private HttpURLConnection httpConn = null;

    public HttpUtils() {}

    private void init(String connectUrl, String method) throws Exception {
        URL url = new URL(connectUrl);
        System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return urlHostName.equals(session.getPeerHost());
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setReadTimeout(60000);
        connection.setConnectTimeout(30000);
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConn = (HttpsURLConnection)connection;
            httpsConn.setSSLSocketFactory(MyX509TrustManager.getInstance().getSSLSocketFactory());
        } else if (connection instanceof HttpURLConnection) {
            @SuppressWarnings("unused")
            HttpURLConnection httpConn = (HttpURLConnection)connection;
        } else {
            throw new Exception("不是http/https协议的url");
        }
        this.httpConn = (HttpURLConnection)connection;
        if ("POST".equals(method)) {
            httpConn.setDoOutput(true);
            httpConn.setDoInput(true);
            // httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        }
        httpConn.setRequestMethod(method);
        httpConn.setUseCaches(false);
        httpConn.setInstanceFollowRedirects(true);
    }

    private void destory() {
        try {
            if (this.httpConn != null) {
                this.httpConn.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String readBytesFromStream(InputStream is) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int readLen;
        byte[] tmpBuf = new byte[4096];
        while ((readLen = is.read(tmpBuf)) > 0) {
            baos.write(tmpBuf, 0, readLen);
        }
        is.close();
        return new String(baos.toByteArray());
    }

    public String sendPost(String url, String params, Map<String, String> header) throws Exception {
        init(url, "POST");

        // 判断 是否有设置 请求头
        for (String key : header.keySet()) {
            httpConn.setRequestProperty(key, header.get(key));
        }

        // 判断 是否有设置请求数据
        if (params != null) {
            // StringBuffer buff = new StringBuffer();
            // for (String key : params.keySet()) {
            // buff.append(key);
            // buff.append('=');
            // buff.append(URLEncoder.encode(params.get(key), "UTF-8"));
            // buff.append('&');
            // }
            // String body = buff.toString();
            // body = body.substring(0, body.length() - 1);
            // System.out.println(body);
            DataOutputStream out = new DataOutputStream(httpConn.getOutputStream());
            // out.write(buff.toString().getBytes("UTF-8"));
            out.write(params.getBytes("UTF-8"));
            out.close();
        }

        String result = readBytesFromStream(httpConn.getInputStream());
        destory();
        return result;
    }

}
