package com.library.util.currency;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
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;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.*;
import java.security.KeyStore;

/**
 * 
 * @ClassName: HttpUtils
 * @Description: http工具类
 * @author: lin
 * @date: 2017年4月26日 上午10:22:44
 * @version:
 */
public class HttpUtils {

	public static Logger logger = LogManager.getLogger(HttpUtils.class);

	/**
	 * 
	 * @Title: sendGet
	 * @Description: 发起GET请求
	 * @param url 请求的URL
	 * @return 响应信息
	 * @returnType: String
	 * @author: lin
	 * @date: 2017年4月26日 上午10:55:36
	 */
	public static String sendGet(String url) {

		String message = null;

		try {
			URL sendURL = new URL(url);
			// 打开连接
			HttpURLConnection connection = (HttpURLConnection) sendURL.openConnection();
			// 设置请求格式
			connection.setRequestMethod("GET");
			// 设置请求头部
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			// 是否输出
			connection.setDoOutput(true);
			// 是否输入
			connection.setDoInput(true);
			// 建立实际的连接
			connection.connect();

			InputStream is = connection.getInputStream();
			int size = is.available();
			byte[] b = new byte[size];
			is.read(b);
			message = new String(b, "UTF-8");

		} catch (MalformedURLException e) {
			logger.error(" url analysis exception ", e);
		} catch (IOException e) {
			logger.error("io exception", e);
			e.printStackTrace();
		}
		return message;
	}

	/**
	 * 
	 * @Title: sendPost
	 * @Description: 发起POST请求
	 * @param url
	 * @param str1
	 * @return
	 * @returnType: String
	 * @author: lin
	 * @date: 2017年5月11日 下午4:04:19
	 */
	public static String sendPost(String url, String str1) {
		try {
			URL sendURL = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) sendURL.openConnection();
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			connection.connect();
			// 建立输出流，并写入数据
			OutputStream outputStream = connection.getOutputStream();
			outputStream.write(str1.getBytes("UTF-8"));
			outputStream.close();

			// 获得响应状态
			int responseCode = connection.getResponseCode();

			if (HttpURLConnection.HTTP_OK == responseCode) {// 连接成功
				// 当正确响应时处理数据
				StringBuffer sb = new StringBuffer();
				String readLine;
				BufferedReader responseReader;
				// 处理响应流，必须与服务器响应流输出的编码一致
				responseReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
				while ((readLine = responseReader.readLine()) != null) {
					sb.append(readLine).append("\n");
				}
				responseReader.close();
				return sb.toString();
			}
		} catch (MalformedURLException e) {
			logger.error(" url analysis exception ", e);
		} catch (IOException e) {
			logger.error("io exception", e);
		}
		return null;
	}
	
	/**
	 * 
	 * @Title: downloadFile
	 * @Description: 下载文件
	 * @param fileUrl 文件路径
	 * @param fileLocal 下载路径
	 * @throws Exception
	 * @returnType: void
	 * @author: lin
	 * @date: 2017年5月6日 下午1:32:02
	 */
	public static void downloadFile(String fileUrl,String fileLocal) throws Exception {
        URL url = new URL(fileUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(6000);
        urlCon.setReadTimeout(6000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        
        //读文件流
        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        out.close();
        in.close();
    }

	/**
	 * 
	 * @Title: getIp
	 * @Description: 得到客户端真实的IP地址
	 * @param request
	 * @return
	 * @returnType: String
	 * @author: lin
	 * @date: May 12, 2017 5:46:07 PM
	 */
	public static String getIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if(!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
            }else{
                return ip;
            }
        }
        ip = request.getHeader("X-Real-IP");
        if(!StringUtils.isEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
        }
        return request.getRemoteAddr();
    }
	
	
	/**
	 * 
	 * @Title: accessXMLData
	 * @Description: 接收xml数据
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws IOException
	 * @throws DocumentException
	 * @returnType: String
	 * @author: lin
	 * @date: May 13, 2017 10:46:16 AM
	 */
	public static String accessXMLData(HttpServletRequest request) throws UnsupportedEncodingException, IOException, DocumentException{
		BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
		String buffer = null;
		StringBuffer xml = new StringBuffer();
		while((buffer = br.readLine()) != null){
			xml.append(buffer);
		}
		Document document = null;
		SAXReader reader = new SAXReader();
		ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.toString().getBytes());
		InputStreamReader ir = new InputStreamReader(inputStream);
		document = reader.read(ir);
		return document.getRootElement().asXML();
	}
	
	/**
	 * 
	 * @Title: accessIP
	 * @Description: 获得本机ip
	 * @return
	 * @throws UnknownHostException
	 * @returnType: String
	 * @author: lin
	 * @date: May 13, 2017 1:20:45 PM
	 */
	public static String accessIP() throws UnknownHostException{
		InetAddress ia = InetAddress.getLocalHost();
		return ia.getHostAddress();
	}
	
	/**
	 * 
	 * @Title: sendCertificatePost
	 * @Description: 发起POST请求 携带证书
	 * @param url
	 * @param str1
	 * @return
	 * @returnType: String
	 * @author: lin
	 * @date: May 13, 2017 11:03:58 AM
	 */
	public static String ssl(String url,String data){
        StringBuffer message = new StringBuffer();
        try {
            String mchId = "1405884002"; //证书密码
            KeyStore keyStore  = KeyStore.getInstance("PKCS12");
            String certFilePath = "E:/wechat/cert/apiclient_cert.p12";
            // linux下
            if ("/".equals(File.separator)) {
                certFilePath = "//usr//local//certs//apiclient_cert.p12";
            }
            FileInputStream instream = new FileInputStream(new File(certFilePath));
            keyStore.load(instream, mchId.toCharArray());
            SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, mchId.toCharArray()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
            HttpPost httpost = new HttpPost(url);
            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            System.out.println("executing request" + httpost.getRequestLine());
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                if (entity != null) {
                    System.out.println("Response content length: " + entity.getContentLength());
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        message.append(text);
                    }
                }
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } 
        return message.toString();
    }
}
