package com.persagy.filemove.util;

import com.alibaba.fastjson.JSONObject;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpTools {
	private final static PoolingHttpClientConnectionManager CONNECTION_MANAGER = new PoolingHttpClientConnectionManager();
	private final static CloseableHttpClient HTTP_CLIENT;
	private static final String UTF8 = "utf-8";

	static {
		// 设置整个连接池最大连接数 根据自己的场景决定
		CONNECTION_MANAGER.setMaxTotal(100);
		// 每个路由(网站)的最大连接数
		CONNECTION_MANAGER.setDefaultMaxPerRoute(50);
		RequestConfig requestConfig = RequestConfig.custom()
				// 与远程主机连接建立时间,三次握手完成时间
				.setConnectTimeout(5000)
				// 建立连接后,数据包传输过程中,两个数据包之间间隔的最大时间
				.setSocketTimeout(10000)
				// httpClient使用连接池来管理连接,这个时间就是从连接池获取连接的超时时间
				.setConnectionRequestTimeout(5000).build();
		HTTP_CLIENT = HttpClients.custom().setConnectionManager(CONNECTION_MANAGER)
				.setDefaultRequestConfig(requestConfig).build();
	}

	public static String httpGetRequest(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		return sendRequest(httpGet);
	}

	public static String httpPostRequest(String url) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		return sendRequest(httpPost);
	}

	public static String httpPostJson(String url, JSONObject param) throws IOException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
		httpPost.setEntity(new StringEntity(param.toJSONString(), UTF8));
		String respContent = sendRequest(httpPost);
		return respContent;
	}
	
	public static String httpPostJson(String url, Map<Object, Object> params) throws IOException {
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
		httpPost.setEntity(new StringEntity(JsonTools.beanToJson(params), UTF8));
		String respContent = sendRequest(httpPost);
		return respContent;
	}
	
	/**
	 * 
	 * @param url http地址
	 * @param params 表单参数{"key":"jsonString"}
	 * @return
	 * @throws IOException
	 */
	public static String httpPostForm(String url, Map<String, Object> params) throws IOException {
		HttpEntity reqEntity = null;
		List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
		for(Map.Entry<String,Object> entry : params.entrySet()){
			pairs.add(new BasicNameValuePair(entry.getKey(),entry.getValue().toString()));
		}
        reqEntity = new UrlEncodedFormEntity(pairs,"UTF-8");
        HttpPost httpPost = new HttpPost(url);
    	if(reqEntity!=null){
    		httpPost.setEntity(reqEntity);
    	}
        
		String respContent = sendRequest(httpPost);
		return respContent;
	}

	private static String sendRequest(HttpUriRequest request) throws IOException {
		CloseableHttpResponse response = HTTP_CLIENT.execute(request);
		return EntityUtils.toString(response.getEntity(), UTF8);
	}

	public static String httpPostRequest(String url, InputStream is) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new InputStreamEntity(is));
		return sendRequest(httpPost);
	}

	public static String httpPostRequest(String url, byte[] bytes) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new ByteArrayEntity(bytes));
		return sendRequest(httpPost);
	}

	public static String httpPostRequest(String url, File file) throws Exception {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new FileEntity(file));
		return sendRequest(httpPost);
	}

	public static byte[] httpGetFile(String url) throws Exception {
		HttpGet httpGet = new HttpGet(url);
		CloseableHttpResponse response = HTTP_CLIENT.execute(httpGet);
		return EntityUtils.toByteArray(response.getEntity());
	}
}