package com.rrtx.services.common.http;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

/**
 * 发送请求
 * @author Zhumq
 *
 */
public class HttpPostUtil {
	/**
	 * 发送get请求
	 * @param url
	 * @param param "a=111&b=123"
	 * @return
	 */
	public static String sendGet(String url,String param){
		String result = "";
		try{
			String urlName = url + "?"+param;//

			URL U = new URL(urlName);
			URLConnection connection = U.openConnection();
			connection.connect();
	  
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine())!= null){
				result += line;
			}	
			in.close();   
		}catch(Exception e){
			System.out.println("error!!"+e);
		}
		return result;
 	}
	/**
	 * 发送post请求
	 * @param url   
	 * @param param "a=111&b=123"
	 * @return
	 */
	public static String sendPost(String url, String param){
		String result = "";
		try{
			URL httpurl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection)httpurl.openConnection();
			httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			PrintWriter out = new PrintWriter(httpConn.getOutputStream());
			out.print(param);
			out.flush();
			out.close();
		   	BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
		   	String line;
		   	while ((line = in.readLine())!= null){
		   		result += line; 
		   	}
		   	in.close();
		}catch(Exception e){
			System.out.println("error!!"+e);
		}
		
		System.out.println("result:"+result);
		return result;
	}
	/**
	 * 发送post请求(推货专用)
	 * @param url   
	 * @param param "a=111&b=123"
	 * @return
	 */
	public static String sendPostFormachine(String url, String param){
		String result = "";
		try{
			param = URLEncoder.encode(param, "utf-8");
			URL httpurl = new URL(url);
			HttpURLConnection httpConn = (HttpURLConnection)httpurl.openConnection();       
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			// 设置传递方式
			httpConn.setRequestMethod("POST");
            // 设置维持长连接
			httpConn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
			httpConn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
			//byte[] data = ("formData=" + param.toString()).getBytes();
            byte[] data = (param.toString()).getBytes();
           // 设置文件长度
            httpConn.setRequestProperty("Content-Length", String.valueOf(data.length));
           // 设置文件类型:
            httpConn.setRequestProperty("contentType", "application/json");
//			PrintWriter out = new PrintWriter(httpConn.getOutputStream());
//			out.print(param.getBytes());
//			out.flush();
//			out.close();
            OutputStream out = new DataOutputStream(httpConn.getOutputStream()) ;
			// 写入请求的字符串
			out.write((param.toString()).getBytes());
			out.flush();
			out.close();

		   	BufferedReader in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
		   	String line;
		   	while ((line = in.readLine())!= null){
		   		result += line; 
		   	}
		   	in.close();
		}catch(Exception e){
			System.out.println("error!!"+e);
		}
		
		System.out.println("result:"+result);
		return result;
	}
	
	
	
	
	
	
	 private final static int CONNECT_TIMEOUT = 5000; // in milliseconds  
     private final static String DEFAULT_ENCODING = "UTF-8";  
     private static int socketTimeout = 10000;// 连接超时时间，默謿10祿
     private static int connectTimeout = 30000;// 传输超时时间，默謿30祿
     
     private static RequestConfig requestConfig;// 请求器的配置
     private static CloseableHttpClient httpClient;// HTTP请求嗿
     
     public static String postData(String urlStr, String data){  
         return postData(urlStr, data, null);  
     }  

     public static String postData(String urlStr, String data, String contentType){  
         BufferedReader reader = null;  
         try {  
             URL url = new URL(urlStr);  
             URLConnection conn = url.openConnection();  
             conn.setDoOutput(true);  
             conn.setConnectTimeout(CONNECT_TIMEOUT);  
             conn.setReadTimeout(CONNECT_TIMEOUT);  
             if(contentType != null)  
                 conn.setRequestProperty("content-type", contentType);  
             OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);  
             if(data == null)  
                 data = "";  
             writer.write(data);   
             writer.flush();  
             writer.close();    

             reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));  
             StringBuilder sb = new StringBuilder();  
             String line = null;  
             while ((line = reader.readLine()) != null) {  
                 sb.append(line);  
                 sb.append("\r\n");  
             }  
             return sb.toString();  
         } catch (IOException e) {  
      	   e.printStackTrace();
         } finally {  
             try {  
                 if (reader != null)  
                     reader.close();  
             } catch (IOException e) {  
             }  
         }  
         return null;  
     }  
     
     /**
      * 通过Https弿API post xml数据
      *
      * @param url API地址
      * @param xmlObj 要提交的XML数据对象
     * @param mchId 商户ID
     * @param certPath 证书位置
      * @return
      */
     public static String postData(String url, String xmlObj, String mchId, String certPath) {
         // 加载证书
         try {
             initCert(mchId, certPath);
         } catch (Exception e) {
             e.printStackTrace();
         }
         String result = null;
         HttpPost httpPost = new HttpPost(url);
         // 得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
         StringEntity postEntity = new StringEntity(xmlObj, "UTF-8");
         httpPost.addHeader("Content-Type", "text/xml");
         httpPost.setEntity(postEntity);
         // 根据默认超时限制初始化requestConfig
         requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).build();
         // 设置请求器的配置
         httpPost.setConfig(requestConfig);
         try {
             HttpResponse response = null;
             try {
                 response = httpClient.execute(httpPost);
             } catch (IOException e) {
                 e.printStackTrace();
             }
             HttpEntity entity = response.getEntity();
             try {
                 result = EntityUtils.toString(entity, "UTF-8");
             } catch (IOException e) {
                 e.printStackTrace();
             }
         } finally {
             httpPost.abort();
         }
         return result;
     }
  
     /**
      * 加载证书
      *
      * @param mchId 商户ID
      * @param certPath 证书位置
      * @throws Exception
      */
     private static void initCert(String mchId, String certPath) throws Exception {
         // 证书密码，默认为商户ID
         String key = mchId;
         // 证书的路弿
         String path = certPath;
         // 指定读取证书格式为PKCS12
         KeyStore keyStore = KeyStore.getInstance("PKCS12");
         // 读取本机存放的PKCS12证书文件
         FileInputStream instream = new FileInputStream(new File(path));
         try {
             // 指定PKCS12的密瞿(商户ID)
             keyStore.load(instream, key.toCharArray());
         } finally {
             instream.close();
         }
         SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, key.toCharArray()).build();
         SSLConnectionSocketFactory sslsf =
                 new SSLConnectionSocketFactory(sslcontext, new String[] {"TLSv1"}, null,
                         SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
         httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
     }
}
