package com.dashitech.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtil {

    public static CloseableHttpClient getHttpClient() {
    	 RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
    	 CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
         return httpClient;
    }

    /**
     * HTTP Get 获取内容
     * @param url  请求的url地址 ?之前的地址
     * @param params	请求的参数
     * @param charset	编码格式
     * @return	页面内容
     */
    public static String doGet(String url,Map<String,String> params,String charset){
    	if(StringUtils.isBlank(url)){
    		return null;
    	}
    	try {
    		if(params != null && !params.isEmpty()){
    			List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
    			for(Map.Entry<String,String> entry : params.entrySet()){
    				String value = entry.getValue();
    				if(value != null){
    					pairs.add(new BasicNameValuePair(entry.getKey(),value));
    				}
    			}
    			url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
    		}
    		HttpGet httpGet = new HttpGet(url);
    		CloseableHttpResponse response = getHttpClient().execute(httpGet);
    		int statusCode = response.getStatusLine().getStatusCode();
    		if (statusCode != 200) {
    			httpGet.abort();
    			throw new RuntimeException("HttpClient,error status code :" + statusCode);
    		}
    		HttpEntity entity = response.getEntity();
    		String result = null;
    		if (entity != null){
    			result = EntityUtils.toString(entity, charset);
    		}
    		EntityUtils.consume(entity);
    		response.close();
    		return result;
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return null;
    }
    
    /**
     * HTTP Post 获取内容
     * @param url  请求的url地址 ?之前的地址
     * @param params	请求的参数
     * @param charset	编码格式
     * @return	页面内容
     */
    public static String doPost(String url,Map<String,String> params,String charset){
    	if(StringUtils.isBlank(url)){
    		return null;
    	}
    	try {
    		List<NameValuePair> pairs = null;
    		if(params != null && !params.isEmpty()){
    			pairs = new ArrayList<NameValuePair>(params.size());
    			for(Map.Entry<String,String> entry : params.entrySet()){
    				String value = entry.getValue();
    				if(value != null){
    					pairs.add(new BasicNameValuePair(entry.getKey(),value));
    				}
    			}
    		}
    		HttpPost httpPost = new HttpPost(url);
    		if(pairs != null && pairs.size() > 0){
    			httpPost.setEntity(new UrlEncodedFormEntity(pairs,charset));
    		}
    		CloseableHttpResponse response = getHttpClient().execute(httpPost);
    		int statusCode = response.getStatusLine().getStatusCode();
    		if (statusCode != 200) {
    			httpPost.abort();
    			throw new RuntimeException("HttpClient,error status code :" + statusCode);
    		}
    		HttpEntity entity = response.getEntity();
    		String result = null;
    		if (entity != null){
    			result = EntityUtils.toString(entity, charset);
    		}
    		EntityUtils.consume(entity);
    		response.close();
    		return result;
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	return null;
    }

	public static void outPrint(HttpServletResponse response, String content, String charset) {
		response.setCharacterEncoding(charset);
		response.setContentType(new StringBuilder().append("text/html;charset=").append(charset).toString());
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.println(content);
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			out.close();
		}
	}
	
	public static String readResponse(String requestUrl, Map<String, String> params, String method, String charset) {
		StringBuffer sb = new StringBuffer();
		String paramsStr = "";
		if ((params != null) && (params.size() > 0)) {
			for (Map.Entry e : params.entrySet()) {
				sb.append((String) e.getKey());
				sb.append("=");
				sb.append((String) e.getValue());
				sb.append("&");
			}
			paramsStr = sb.substring(0, sb.length() - 1);
		}
		return readResponse(requestUrl, paramsStr, method, charset);
	}
	
	public static String readPostResponse(String requestUrl, String json, String contentType) {
		HttpURLConnection conn = null;
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String line = null;
		try {
			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", contentType);
			conn.setRequestProperty("Accept-Charset", "UTF-8");
			conn.setRequestProperty("Content-Length", new StringBuilder().append("").append(json.length()).toString());
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(json);
			out.flush();
			out.close();

			if (conn.getResponseCode() != 200) {
				System.err.println("connect failed!" + conn.getResponseCode());
				String str1 = "";
				return str1;
			}
			String result = "";
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			while ((line = in.readLine()) != null) {
				result = new StringBuilder().append(result).append(line).append("\n").toString();
			}
			String str2 = result;
			return str2;
		} catch (SocketException se) {
			se.printStackTrace();
			line = null;
			return line;
		} catch (Exception e) {
			e.printStackTrace();
			line = null;
			return line;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null)
				conn.disconnect();
		}
	}
	
	public static String readResponse(String requestUrl, String requestData, String method, String charset) {
		HttpURLConnection conn = null;
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String line = null;
		try {
			URL url = new URL(requestUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod(method);
			conn.setRequestProperty("Content-Type", "text/html");
			conn.setRequestProperty("Accept-Charset", charset);
			conn.setUseCaches(false);
			conn.setDoOutput(true);
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Content-Length", new StringBuilder().append("").append(requestData.length()).toString());
			out = new OutputStreamWriter(conn.getOutputStream(), charset);
			out.write(requestData);
			out.flush();
			out.close();

			if (conn.getResponseCode() != 200) {
				System.err.println("connect failed!" + conn.getResponseCode());
				String str1 = "";
				return str1;
			}
			String result = "";
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
			while ((line = in.readLine()) != null) {
				result = new StringBuilder().append(result).append(line).append("\n").toString();
			}
			String str2 = result;
			return str2;
		} catch (SocketException se) {
			se.printStackTrace();
			line = null;
			return line;
		} catch (Exception e) {
			e.printStackTrace();
			line = null;
			return line;
		} finally {
			if (out != null) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (conn != null)
				conn.disconnect();
		}
	}

	public static String getString(byte[] b, int offset, int len, String encoding) {
		try {
			return new String(b, offset, len, encoding);
		} catch (UnsupportedEncodingException e) {
		}
		return new String(b, offset, len);
	}


	public static String doPost(String httpUrl,Object param) {

		HttpURLConnection connection = null;
		InputStream is = null;
		OutputStream out = null;
		BufferedReader br = null;
		String result = null;
		try {
			URL url = new URL(httpUrl);
			// 通过远程url连接对象打开连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接请求方式
			connection.setRequestMethod("POST");
			// 设置连接主机服务器超时时间：15000毫秒
			connection.setConnectTimeout(60000);
			// 设置读取主机服务器返回数据超时时间：60000毫秒
			connection.setReadTimeout(60000);

			// 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
			connection.setDoOutput(true);
			// 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
			connection.setDoInput(true);
			// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
			connection.setRequestProperty("Content-Type", "application/json");
			// 设置鉴权信息：Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
			//connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");
			// 通过连接对象获取一个输出流
			out = connection.getOutputStream();
			// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
			//os.write(param.getBytes());
			//JSONObject obj = new JSONObject();
			// java.net.URLEncoder.encode 编码之后会有%多余%的问题，在传输的过程中无法被解析
			// String json = java.net.URLEncoder.encode(obj.toString(), "utf-8");
			Object o = JSONObject.toJSON(param);
			Object jsonObject = JSONObject.parse(o.toString());
			out.write(jsonObject.toString().getBytes());


			// 通过连接对象获取一个输入流，向远程读取
			if (connection.getResponseCode() == 200) {

				is = connection.getInputStream();
				// 对输入流对象进行包装:charset根据工作项目组的要求来设置
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

				StringBuffer sbf = new StringBuffer();
				String temp = null;
				// 循环遍历一行一行读取数据
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 断开与远程地址url的连接
			connection.disconnect();
		}
		return result;
	}
	public static void main(String[] args) {
		String re=readResponse("www.baidu.com","","get","UTF-8");
		System.out.println(re);
	}
}