package com.util;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.TrustManager;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

public class HttpUtil2 {

    public static String doPost (String url, String param, Map headerparam) throws Exception {
        URL reqURL = new URL(url); //创建URL对象
        HttpURLConnection httpsConn = (HttpURLConnection) reqURL.openConnection();
        httpsConn.setDoOutput(true);
        httpsConn.setRequestMethod("POST");
//        httpsConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        httpsConn.setRequestProperty("Accept-Charset", "utf-8");
        httpsConn.setRequestProperty("contentType", "utf-8");
        httpsConn.setRequestProperty("Content-Length", param.length()
                + "");


        if(headerparam != null){
            Set<String> keys =headerparam.keySet();
            Iterator<String> iterator = keys.iterator();
            while(iterator.hasNext()){
                String key =iterator.next().toString();
                String value = headerparam.get(key).toString();
                httpsConn.setRequestProperty(key,value);
            }
        }


        OutputStreamWriter out = new OutputStreamWriter(httpsConn.getOutputStream(), "utf-8");
        out.write(param.toString());
        out.flush();
        out.close();
//取得该连接的输入流，以读取响应内容
        InputStreamReader insr = new InputStreamReader(httpsConn.getInputStream(), "utf-8");

//读取服务器的响应内容并显示
        String result = "";
        int respInt = insr.read();
        while (respInt != -1) {
            result += (char) respInt;
            respInt = insr.read();
        }
        return result;
    }


}
