package com.sino.weixin.oauth.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

public class HttpsUtil {
	 private static CloseableHttpClient httpClient;
	 public static final String CHARSET = "UTF-8";
	 
	 static {
	        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
	        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	    }
	 
	private static class TrustAnyTrustManager implements X509TrustManager {
		  
        @Override
		public void checkClientTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
  
        @Override
		public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }
  
        @Override
		public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[] {};
        }
    }
  
    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        @Override
		public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
    
    
    /**
     * post方式请求服务器(https协议)
     *
     * @param url
     *            请求地址
     *            参数
     *            编码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */ 
    public static String sendPost(String url, String param) {
    	DataOutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
        	SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
                    new java.security.SecureRandom());
      
            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
            conn.setDoOutput(true);
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            out.write(param.getBytes("UTF-8"));
            // 刷新、关闭
            out.flush();
            out.close();
            
         // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
               
            }
            byte[] b = result.getBytes("GBK");  
            result = new String(b,"UTF-8"); 
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    } 
  
    /**
     * post方式请求服务器(https协议)
     *
     * @param url
     *            请求地址
     *            参数json格式
     *            编码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */ 
    public static String sendPostJSON(String url, String param) {
    	DataOutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
        	SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
                    new java.security.SecureRandom());
      
            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
           
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());            
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type","application/json");
            
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            out.write(param.getBytes("UTF-8"));
            // 刷新、关闭
            out.flush();
            out.close();
            
         // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
               
            }
            byte[] b = result.getBytes();  
            result = new String(b,"UTF-8"); 
        } catch (Exception e) {
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    } 
    
    
    public static String doPost(String url,JSONObject json,String charset){
        if(StringUtils.isBlank(url)){
            return null;
        }
        try {
            List<NameValuePair> pairs = null;
            if(json != null && json.size()>0){
                pairs = new ArrayList<NameValuePair>(json.size());
                for(Entry<String, Object> entry : json.entrySet()){
                    String value = entry.getValue().toString();
                    if(value != null){
                        pairs.add(new BasicNameValuePair(entry.getKey(),value));
                    }
                }
            }
            HttpPost httpPost = new HttpPost(url);
            if(pairs != null && pairs.size() > 0){
                httpPost.setEntity(new UrlEncodedFormEntity(pairs,CHARSET));
            }
            System.out.println(httpPost.getURI());
            
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null){
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static void main(String[] args) {
    	JSONObject jsonObject=new JSONObject();
		//jsonObject.put("rescueCode", "DJWY57");
		//String array = (HttpsUtil.doPost("http://175.102.6.163:8380/RescueCompanyWeixinServlet.do?action=6", jsonObject,"UTF-8"));
		
		jsonObject.put("loginName", "NTLJ");
		jsonObject.put("password", "1111");
		jsonObject.put("action", 1);
		Map<String,Object> systemUserPO=JSON.parseObject(HttpsUtil.doPost(Constants.url, jsonObject, "utf-8"));
		System.out.println("数组==="+systemUserPO);
	}
    
}
