/** 
 * @Title: Http.java 
 * @Package com.zhiweidata.bjfzxWebapp.htttpClient 
 * @Description: TODO(用一句话描述该文件做什么) 
 * @author xuyimeng 
 * @date 2018年2月6日 上午10:31:58 
 * @version V1.0 
 */ /**
 * 
 */
package com.zhiweidata.bjfzxWebapp.htttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpStatus;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

/** 
 * @ClassName: Http 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author xuyimeng 
 * @date 2018年2月6日 上午10:31:58  
 */
public class HttpClientTemplate {
	
	@Test
	public void test()
	{
		String url = "http://short.weixin.qq.com/cgi-bin/micromsg-bin/geta8key HTTP/1.1";
		
		Map<String,String> headerMap = new HashMap<String,String>();
		headerMap.put("Accept-Encoding", "gzip");
		headerMap.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Mobile/13C75 MicroMessenger/6.3.9 NetType/WIFI Language/zh_CN");
		headerMap.put("Accept", "*/*");
		headerMap.put("Accept-Language", "zh-CN,zh;q=0.8");
		headerMap.put("Cache-Control", "max-age=0");
		headerMap.put("Connection", "keep-alive");
		headerMap.put("Host", "short.weixin.qq.com");
		headerMap.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		headerMap.put(
				"User-Agent",
				"MicroMessenger Client");
		headerMap.put("If-Modified-Since", String.valueOf(new Date()));
		
		String htmlBody = null;
		try {
			htmlBody = requestByPostMethod(url,headerMap,null,null);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("=="+htmlBody);
	}
	
	
	
	 /**
	  * @Title: executeHttpRequestGet 
	  * @Description: TODO(Get请求) 
	  * @param @param url
	  * @param @param headerMap
	  * @param @return
	  * @param @throws Exception 设定文件 
	  * @return String 返回类型
	  */
	 public String executeHttpRequestGet(String url,
			 Map<String,String> headerMap) throws Exception
	 {
		 return executeHttpRequestGet(url,headerMap,null);
	 }
	
	 /**
	  * @Title: executeHttpRequestGet 
	  * @Description: TODO(Get请求+代理IP) 
	  * @param @param url
	  * @param @param headerMap
	  * @param @param proxy
	  * @param @param host
	  * @param @return
	  * @param @throws Exception 设定文件 
	  * @return String 返回类型
	  */
	 public String executeHttpRequestGet(String url,
			 Map<String,String> headerMap,String proxy,int host)
					 throws Exception
	 {
		 HttpHost httpHost = new HttpHost(proxy,host);
		 return executeHttpRequestGet(url,headerMap,httpHost);
	 }
	
	
	 /**
	  * @Title: requestByPostMethod 
	  * @Description: TODO(Post请求处理) 
	  * @param @param url
	  * @param @param params
	  * @param @param headerMap
	  * @param @return
	  * @param @throws Exception 设定文件 
	  * @return String 返回类型
	  */
	 public String requestByPostMethod(String url, Map<String,String> params
			 ,Map<String,String> headerMap) throws Exception
	 {
		 return requestByPostMethod(url,params,headerMap,null);
	 }
	 
	 
	 /**
	  * @Title: requestByPostMethod 
	  * @Description: TODO(Post请求+代理IP处理) 
	  * @param @param url
	  * @param @param params
	  * @param @param headerMap
	  * @param @param proxy
	  * @param @param host
	  * @param @return
	  * @param @throws Exception 设定文件 
	  * @return String 返回类型
	  */
	 public String requestByPostMethod(String url, Map<String,String> params
			 ,Map<String,String> headerMap,String proxy,int host) throws Exception
	 {
		 HttpHost httpHost = new HttpHost(proxy,host);
		 return requestByPostMethod(url,params,headerMap,httpHost);
	 }
	 
	/**
	 * @Title: executeHttpRequestGet 
	 * @Description: TODO(Get请求) 
	 * @param @param url
	 * @param @param headerMap
	 * @param @return
	 * @param @throws Exception 设定文件 
	 * @return String 返回类型
	 */
    public String executeHttpRequestGet(String url,Map<String,String> headerMap
    		,HttpHost httpHost) throws Exception
    {
        //创建默认的httpClient实例
    	String result = null;
        CloseableHttpClient httpClient = getHttpClient();
        
        CloseableHttpResponse httpResponse = null;
        try {
            //用get方法发送http请求
            HttpGet getMethod = new HttpGet(url);
            RequestConfig requestConfig = null;
            if(httpHost!=null)
            {
            	//设置请求和传输超时时间
                requestConfig = RequestConfig.custom()
                			.setSocketTimeout(5000)
                			.setConnectTimeout(5000)
                			.setProxy(httpHost)
                			.build();
            }else
            {
            	//设置请求和传输超时时间
                requestConfig = RequestConfig.custom()
                			.setSocketTimeout(5000)
                			.setConnectTimeout(5000)
                			.build();
            }
            
            getMethod.setConfig(requestConfig);
            //设置请求头信息
            if(headerMap!=null)
            {
            	for(Entry<String, String> header : headerMap.entrySet())
                {
            		getMethod.setHeader(header.getKey(), header.getValue());
                }
            }
            //发送get请求
            httpResponse = httpClient.execute(getMethod);
            try{
                //设置重连3次
            	boolean f = true;
            	int i = 1;
            	while(f)
            	{
            		//response实体
            		HttpEntity entity = httpResponse.getEntity();
                    if (null != entity){
                    	result = EntityUtils.toString(entity,"UTF-8");
    					EntityUtils.consume(entity);
    					getMethod.releaseConnection();
//    					//清楚浏览器缓存
    					httpResponse.setHeader("Cache-Control","no-store");
    					httpResponse.setHeader("Pragrma","no-cache");
    					httpResponse.close();
    					f = false;
                    }else
                    {
                    	if(i==3)
                    	{
                    		i = 1;
                    		f = false;
                    	}
                    }
            	}
            }
            finally{
                httpResponse.close();
            }
        } catch (Exception e) {
            new Exception(e);
        }
        finally{
            try{
                closeHttpClient(httpClient);
            } catch (IOException e){
                new Exception(e);
            }
        }
        return result;
    }
     
     
    /**
     * @Title: requestByPostMethod 
     * @Description: TODO(post请求) 
     * @param @param url
     * @param @param params
     * @param @param headerMap
     * @param @return 设定文件 
     * @return String 返回类型
     */
    public String requestByPostMethod(String url, Map<String,String> params
    		,Map<String,String> headerMap,HttpHost httpHost) throws Exception
     {
    	String result = null;
        CloseableHttpClient httpClient = getHttpClient();
        try {
            HttpPost postMethod = new HttpPost(url);          //这里用上本机的某个工程做测试
            //设置超时提醒和代理ip
            RequestConfig requestConfig = null;
            if(httpHost!=null)
            {
            	//设置请求和传输超时时间
                requestConfig = RequestConfig.custom()
                			.setSocketTimeout(5000)
                			.setConnectTimeout(5000)
                			.setProxy(httpHost)
                			.build();
            }else
            {
            	//设置请求和传输超时时间
                requestConfig = RequestConfig.custom()
                			.setSocketTimeout(5000)
                			.setConnectTimeout(5000)
                			.build();
            }
            postMethod.setConfig(requestConfig);
            
            //创建参数列表
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            if(params!=null)
            {
            	for(Entry<String,String> param : params.entrySet())
                {
                	list.add(new BasicNameValuePair(param.getKey(), param.getValue()));
                }
            }
            
            //创建请求头信息列表
            for(Entry<String, String> header : headerMap.entrySet())
            {
            	postMethod.setHeader(header.getKey(), header.getValue());
            }
            
            //url格式编码
            UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list,"UTF-8");
            postMethod.setEntity(uefEntity);
            //执行请求
            CloseableHttpResponse httpResponse = httpClient.execute(postMethod);
            try{
	            if(httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
	            {
	            	HttpEntity entity = httpResponse.getEntity();
					if (null != entity) {
						InputStream in = entity.getContent();
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(in, "UTF-8"));
						StringBuilder sb = new StringBuilder();
						String line = null;
						while ((line = reader.readLine()) != null) {
							sb.append(line);
						}
						result = sb.toString();
						reader.close();
						in.close();
						postMethod.releaseConnection();
						// //清楚浏览器缓存
						httpResponse.setHeader("Cache-Control", "no-store");
						httpResponse.setHeader("Pragrma", "no-cache");
						httpResponse.close();
						EntityUtils.consume(entity);
					}
	            }
            } finally{
                httpResponse.close();
            } 
             
        } catch( UnsupportedEncodingException e){
            e.printStackTrace();
            new Exception(e);
        }
        catch (IOException e) {
            e.printStackTrace();
            new Exception(e);
        }
        finally{
            try{
                closeHttpClient(httpClient);                
            } catch(Exception e){
                e.printStackTrace();
                new Exception(e);
            }
        }
        return result;
    }
    
    /**
     * @Title: getHttpClient 
     * @Description: TODO(释放连接) 
     * @param @return 设定文件 
     * @return CloseableHttpClient 返回类型
     */
    private CloseableHttpClient getHttpClient(){
        return HttpClients.createDefault();
    }
     
    /**
     * @Title: closeHttpClient 
     * @Description: TODO(关闭连接) 
     * @param @param client
     * @param @throws IOException 设定文件 
     * @return void 返回类型
     */
    private void closeHttpClient(CloseableHttpClient client) throws IOException{
        if (client != null){
            client.close();
        }
    }
}