package com.chinacreator.video.restful.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

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

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.*; 

public class HttpInvoke {
	
	protected static Logger log = Logger.getLogger(HttpInvoke.class);
	
	private static class TrustAnyTrustManager implements X509TrustManager {  
		     
	   public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		   
	   }  
	 
	   public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		   
	   }  
	 
	   public X509Certificate[] getAcceptedIssuers() {  
	       return new X509Certificate[]{};  
	   }  
	}  
	     
	private static class TrustAnyHostnameVerifier implements HostnameVerifier {  
		public boolean verify(String hostname, SSLSession session) {  
		     return true;  
		}  
	} 
	
	/**
	 * 处理https请求
	 * @param method
	 * @param url
	 * @param content
	 * @param reqProperty
	 * @return
	 */
	public static String sendhttpsReq(String method, String url, String content, Map reqProperty){
		StringBuffer buffer = new StringBuffer();
    	HttpsURLConnection connection = null;
    	BufferedReader reader = null;
    	OutputStream out = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
    	try {
			SSLContext sc = SSLContext.getInstance("SSL");
			sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());  
			connection = (HttpsURLConnection) new URL(url).openConnection();
			connection.setSSLSocketFactory(sc.getSocketFactory());  
			connection.setHostnameVerifier(new TrustAnyHostnameVerifier());  
			connection.setRequestMethod(method);
			connection.setDoOutput(true);
			connection.setDoInput(true);
			//设置超时时间为30秒
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			
			if(reqProperty != null && reqProperty.size()>0){
				Set keySet = reqProperty.keySet();
				Iterator iterator = keySet.iterator();
				String key = "";
				String value = "";
				while(iterator.hasNext()){
					key = (String)iterator.next(); 
					value = (String)reqProperty.get(key);
					connection.setRequestProperty(key, value);
				}
			}
			
			connection.connect();
			out = connection.getOutputStream();
			out.write(content.getBytes("UTF-8"));
			out.flush();
			
			if (200 != connection.getResponseCode()) {

			}else{
				inputStream = connection.getInputStream();
				inputStreamReader = new InputStreamReader(inputStream, "utf-8");
				reader = new BufferedReader(inputStreamReader);

				String line = "";
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				reader.close();
			}
		} catch (IOException e) {
			log.error("调HTTP请求出现IO异常："+e.getMessage());
		} catch (Exception e){
			log.error("调HTTP请求出现异常："+e.getMessage());
		} finally {
			if(inputStreamReader != null){
				try {
					inputStreamReader.close();
				} catch (IOException e) {
					inputStreamReader = null;
					log.error("释放inputStreamReader异常："+e.getMessage());
				}
			}
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (IOException e) {
					inputStream = null;
					log.error("释放inputStream异常："+e.getMessage());
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					out = null;
					log.error("释放out异常："+e.getMessage());
				}
			}
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					reader = null;
					log.error("释放reader异常："+e.getMessage());
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
    }
	
	/** 
	 * 连接到服务器并获取数据
	 * GET方式发起请求
	 * @param urlStr 请求URL
	 * @param content 请求报文
	 * @return
	 */
	public static String sendHttpByGet(String urlStr, String content, Map reqProperty) {
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
    	BufferedReader reader = null;
    	OutputStream out = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		try {
			url = new URL(urlStr+"/"+URLEncoder.encode(content,"UTF-8"));	
			connection = (HttpURLConnection) url.openConnection();
			
			if(reqProperty != null && reqProperty.size()>0){
				Set keySet = reqProperty.keySet();
				Iterator iterator = keySet.iterator();
				String key = "";
				String value = "";
				while(iterator.hasNext()){
					key = (String)iterator.next(); 
					value = (String)reqProperty.get(key);
					connection.setRequestProperty(key, value);
				}
			}
			//设置超时时间为30秒
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			connection.connect();

			if (200 != connection.getResponseCode()) {
			   
			}else{
				inputStream = connection.getInputStream();
				inputStreamReader = new InputStreamReader(inputStream, "utf-8");
				reader = new BufferedReader(inputStreamReader);

				String line = "";
				while ((line = reader.readLine()) != null) {
					buffer.append(line);
				}
				reader.close();
			}
		} catch (IOException e) {
			log.error("调HTTP请求出现IO异常："+e.getMessage());
		} catch (Exception e){
			log.error("调HTTP请求出现异常："+e.getMessage());
		} finally {
			if(inputStreamReader != null){
				try {
					inputStreamReader.close();
				} catch (IOException e) {
					inputStreamReader = null;
					log.error("释放inputStreamReader异常："+e.getMessage());
				}
			}
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (IOException e) {
					inputStream = null;
					log.error("释放inputStream异常："+e.getMessage());
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					out = null;
					log.error("释放out异常："+e.getMessage());
				}
			}
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					reader = null;
					log.error("释放reader异常："+e.getMessage());
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}
	
	/**
	 * 连接到服务器并获取数据
	 * POST方式发起请求
	 * @param method 请求方法，POST/PUT 
	 * @param urlStr 请求URL
	 * @param content 请求报文
	 * @param reqProperty 请求属性
	 * @return
	 */
	public static String sendHttpByPost(String method, String urlStr, String content, Map reqProperty){
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
    	BufferedReader reader = null;
    	DataOutputStream out = null;
		InputStream inputStream = null;
		InputStreamReader inputStreamReader = null;
		try {
			url = new URL(urlStr);	
			connection = (HttpURLConnection) url.openConnection();
			if(reqProperty != null && reqProperty.size()>0){
				Set keySet = reqProperty.keySet();
				Iterator iterator = keySet.iterator();
				String key = "";
				String value = "";
				while(iterator.hasNext()){
					key = (String)iterator.next(); 
					value = (String)reqProperty.get(key);
					connection.setRequestProperty(key, value);
				}
			}
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod(method);
			connection.setUseCaches(false);
			//设置超时时间为30秒
			connection.setConnectTimeout(30000);
			connection.setReadTimeout(30000);
			connection.connect();

			out = new DataOutputStream(connection.getOutputStream());
			out.write(content.getBytes("utf-8"));
			out.flush();
			out.close();

			inputStream = connection.getInputStream();
			inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			reader = new BufferedReader(inputStreamReader);
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			
			reader.close();			
		} catch (IOException e) {
			log.error("调HTTP请求出现IO异常："+e.getMessage());
		} catch (Exception e){
			log.error("调HTTP请求出现异常："+e.getMessage());
		} finally {
			if(inputStreamReader != null){
				try {
					inputStreamReader.close();
				} catch (IOException e) {
					inputStreamReader = null;
					log.error("释放inputStreamReader异常："+e.getMessage());
				}
			}
			if(inputStream != null){
				try {
					inputStream.close();
				} catch (IOException e) {
					inputStream = null;
					log.error("释放inputStream异常："+e.getMessage());
				}
			}
			if(out != null){
				try {
					out.close();
				} catch (IOException e) {
					out = null;
					log.error("释放out异常："+e.getMessage());
				}
			}
			if(reader != null){
				try {
					reader.close();
				} catch (IOException e) {
					reader = null;
					log.error("释放reader异常："+e.getMessage());
				}
			}
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}
}
