package com.palmnest.application.core.util;


import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.commons.lang.StringUtils;
import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
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.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.palmnest.application.bean.Attachment;

/**
 * https 请求 微信为https的请求
 *
 * @author yb
 * @date 2014-04-10
 */
public class HttpKit {

	private static final String DEFAULT_CHARSET = "UTF-8";

	private static Logger LOGGER = Logger.getLogger(HttpKit.class);

	/**
	 * 发送Get请求
	 *
	 * @param url
	 * @return
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 * @throws KeyManagementException
	 */
	public static String get(String url) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
		StringBuffer bufferRes = null;
		TrustManager[] tm = {new MyX509TrustManager()};
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL urlGet = new URL(url);
		HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
		// 连接超时
		http.setConnectTimeout(25000);
		// 读取超时 --服务器响应比较慢，增大时间
		http.setReadTimeout(25000);
		http.setRequestMethod("GET");
		http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		http.setSSLSocketFactory(ssf);
		http.setDoOutput(true);
		http.setDoInput(true);
		http.connect();

		InputStream in = http.getInputStream();
		BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
		String valueString = null;
		bufferRes = new StringBuffer();
		while ((valueString = read.readLine()) != null) {
			bufferRes.append(valueString);
		}
		in.close();
		if (http != null) {
			// 关闭连接
			http.disconnect();
		}
		return bufferRes.toString();
	}

	/**
	 * 发送Get请求
	 *
	 * @param url
	 * @return
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 * @throws KeyManagementException
	 */
	public static String get(String url, Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
		if (https != null && https) {
			return get(url);
		} else {
			StringBuffer bufferRes = null;
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			// 连接超时
			http.setConnectTimeout(25000);
			// 读取超时 --服务器响应比较慢，增大时间
			http.setReadTimeout(25000);
			http.setRequestMethod("GET");
			http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();

			InputStream in = http.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
			String valueString = null;
			bufferRes = new StringBuffer();
			while ((valueString = read.readLine()) != null) {
				bufferRes.append(valueString);
			}
			in.close();
			if (http != null) {
				// 关闭连接
				http.disconnect();
			}
			return bufferRes.toString();
		}
	}

	
	
	/**
	 * 发送Get请求
	 *
	 * @param url
	 * @return
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws IOException
	 * @throws KeyManagementException
	 */
	public static String holidayGet(String url, Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
		if (https != null && https) {
			return get(url);
		} else {
			StringBuffer bufferRes = null;
			URL urlGet = new URL(url);
			HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
			// 连接超时
			http.setConnectTimeout(25000);
			// 读取超时 --服务器响应比较慢，增大时间
			http.setReadTimeout(25000);
			http.setRequestMethod("GET");
			//http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			http.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();

			InputStream in = http.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
			String valueString = null;
			bufferRes = new StringBuffer();
			while ((valueString = read.readLine()) != null) {
				bufferRes.append(valueString);
			}
			in.close();
			if (http != null) {
				// 关闭连接
				http.disconnect();
			}
			return bufferRes.toString();
		}
	}
	
	
	/**
	 * 发送Get请求
	 *
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static String get(String url, Map<String, String> params) throws KeyManagementException, NoSuchAlgorithmException, NoSuchProviderException, IOException {
		return get(initParams(url, params));
	}

	/**
	 * 发送Post请求
	 *
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws NoSuchProviderException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static String post(String url, String params) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		StringBuffer bufferRes = null;
		TrustManager[] tm = {new MyX509TrustManager()};
		SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
		sslContext.init(null, tm, new java.security.SecureRandom());
		// 从上述SSLContext对象中得到SSLSocketFactory对象
		SSLSocketFactory ssf = sslContext.getSocketFactory();

		URL urlGet = new URL(url);
		HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
		// 连接超时
		http.setConnectTimeout(25000);
		// 读取超时 --服务器响应比较慢，增大时间
		http.setReadTimeout(25000);
		http.setRequestMethod("POST");
		http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		http.setSSLSocketFactory(ssf);
		http.setDoOutput(true);
		http.setDoInput(true);
		http.connect();

		OutputStream out = http.getOutputStream();
		out.write(params.getBytes("UTF-8"));
		out.flush();
		out.close();

		InputStream in = http.getInputStream();
		BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
		String valueString = null;
		bufferRes = new StringBuffer();
		while ((valueString = read.readLine()) != null) {
			bufferRes.append(valueString);
		}
		in.close();
		if (http != null) {
			// 关闭连接
			http.disconnect();
		}
		return bufferRes.toString();
	}


	/**
	 * 普通HTTP POST请求接口
	 *
	 * @param postData 参数,格式：userid=&account=账号
	 * @param postUrl  请求地址
	 * @return
	 */
	public static String Post(String postData, String postUrl) {
		try {
			//发送POST请求
			URL url = new URL(postUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("POST");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			conn.setRequestProperty("Connection", "Keep-Alive");
			conn.setUseCaches(false);
			conn.setDoOutput(true);

			conn.setRequestProperty("Content-Length", "" + postData.length());
			OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			out.write(postData);
			out.flush();
			out.close();

			//获取响应状态
			if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
				LOGGER.info("connect failed!");
				return "";
			}
			//获取响应内容体
			String line, result = "";
			BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			while ((line = in.readLine()) != null) {
				result += line + "\n";
			}
			in.close();
			return result;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * post raw请求 row json 格式
	 *
	 * @param postData
	 * @param postUrl  调用.net系统接口
	 * @return
	 */
	public static String HttpClientPost(String postData, String postUrl) {

		String result = "";
		try {

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(postUrl);
			StringEntity postingString = new StringEntity(postData, "UTF-8");//UTF-8 不然会有乱码 设置其他无效
			post.setEntity(postingString);
			post.setHeader("Content-type", "application/json");//row json 格式
			HttpResponse response = httpClient.execute(post);
			String content = EntityUtils.toString(response.getEntity());
			result = content;

		} catch (IOException e) {
			e.printStackTrace();
			result = e.getMessage();
		}
		return result;
	}

	/**
	 * post raw请求 row json 格式
	 *
	 * @param postData
	 * @param postUrl  调用.net系统接口
	 * @return
	 */
	public static String HttpClientPost(String postData, String token, String postUrl) {

		String result = "";
		try {

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(postUrl);
			StringEntity postingString = new StringEntity(postData, "UTF-8");//UTF-8 不然会有乱码 设置其他无效
			post.setEntity(postingString);
			post.setHeader("Content-type", "application/json");//row json 格式
			post.setHeader("token", token);//row json 格式
			HttpResponse response = httpClient.execute(post);
			String content = EntityUtils.toString(response.getEntity());
			result = content;

		} catch (IOException e) {
			e.printStackTrace();
			result = e.getMessage();
		}
		return result;
	}

	/**
	 * post raw请求 raw application/x-www-form-urlencoded
	 *
	 * @param postData
	 * @param postUrl
	 * @return
	 */
	public static String HttpPost(String postData, String postUrl) {

		String result = "";
		try {

			HttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(postUrl);
			StringEntity postingString = new StringEntity(postData, "UTF-8");//UTF-8 不然会有乱码 设置其他无效
			post.setEntity(postingString);
			post.setHeader("Content-type", "application/x-www-form-urlencoded");
			HttpResponse response = httpClient.execute(post);
			String content = EntityUtils.toString(response.getEntity());
			result = content;

		} catch (IOException e) {
			e.printStackTrace();
			result = e.getMessage();
		}
		LOGGER.info("HttpPost-result:"+result);
		return result;
	}
	
	public static String HttpPost2(String postData, String postUrl,int type) throws IOException {

		String result = "";
		try {
			
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(postUrl);
			StringEntity postingString = new StringEntity(postData, "UTF-8");//UTF-8 不然会有乱码 设置其他无效
			post.setEntity(postingString);
			if(1 != type){
				//请求超时
				httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 4000);
				//读取超时
				httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,4000);
			}
			post.setHeader("Content-type", "application/x-www-form-urlencoded");
			HttpResponse response = httpClient.execute(post);
			String content = EntityUtils.toString(response.getEntity());
			result = content;
		} catch (IOException e) {
			e.printStackTrace();
			throw new IOException(e.getMessage());
		}
		LOGGER.info("HttpPost-result:"+result);
		return result;
	}

	/**
	 * 向指定URL发送GET方法的请求
	 *
	 * @param url   发送请求的URL
	 * @param param 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			LOGGER.info("realUrl:" + realUrl);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 上传媒体文件
	 *
	 * @param url
	 * @param params
	 * @param file
	 * @return
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchProviderException
	 * @throws KeyManagementException
	 */
	public static String upload(String url, File file) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
		String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // 定义数据分隔线
		StringBuffer bufferRes = null;
		URL urlGet = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "Keep-Alive");
		conn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

		OutputStream out = new DataOutputStream(conn.getOutputStream());
		byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
		StringBuilder sb = new StringBuilder();
		sb.append("--");
		sb.append(BOUNDARY);
		sb.append("\r\n");
		sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
		sb.append("Content-Type:application/octet-stream\r\n\r\n");
		byte[] data = sb.toString().getBytes();
		out.write(data);
		DataInputStream fs = new DataInputStream(new FileInputStream(file));
		int bytes = 0;
		byte[] bufferOut = new byte[1024];
		while ((bytes = fs.read(bufferOut)) != -1) {
			out.write(bufferOut, 0, bytes);
		}
		out.write("\r\n".getBytes()); //多个文件时，二个文件之间加入这个
		fs.close();
		out.write(end_data);
		out.flush();
		out.close();

		// 定义BufferedReader输入流来读取URL的响应
		InputStream in = conn.getInputStream();
		BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
		String valueString = null;
		bufferRes = new StringBuffer();
		while ((valueString = read.readLine()) != null) {
			bufferRes.append(valueString);
		}
		in.close();
		if (conn != null) {
			// 关闭连接
			conn.disconnect();
		}
		return bufferRes.toString();
	}

	/**
	 * 下载资源
	 *
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static Attachment download(String url) throws IOException {
		Attachment att = new Attachment();
		URL urlGet = new URL(url);
		HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
		conn.setDoOutput(true);
		conn.setDoInput(true);
		conn.setUseCaches(false);
		conn.setRequestMethod("GET");
		conn.connect();
		if (conn.getContentType().equalsIgnoreCase("text/plain")) {
			// 定义BufferedReader输入流来读取URL的响应
			InputStream in = conn.getInputStream();
			BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
			String valueString = null;
			StringBuffer bufferRes = new StringBuffer();
			while ((valueString = read.readLine()) != null) {
				bufferRes.append(valueString);
			}
			in.close();
			att.setError(bufferRes.toString());
		} else {
			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			String ds = conn.getHeaderField("Content-disposition");
			String fullName = ds.substring(ds.indexOf("filename=\"") + 10, ds.length() - 1);
			String relName = fullName.substring(0, fullName.lastIndexOf("."));
			String suffix = fullName.substring(relName.length() + 1);

			att.setFullName(fullName);
			att.setFileName(relName);
			att.setSuffix(suffix);
			att.setContentLength(conn.getHeaderField("Content-Length"));
			att.setContentType(conn.getHeaderField("Content-Type"));

			att.setFileStream(bis);
		}
		return att;
	}

	/**
	 * 构造url
	 *
	 * @param url
	 * @param params
	 * @return
	 */
	private static String initParams(String url, Map<String, String> params) {
		if (null == params || params.isEmpty()) {
			return url;
		}
		StringBuilder sb = new StringBuilder(url);
		if (url.indexOf("?") == -1) {
			sb.append("?");
		} else {
			sb.append("&");
		}
		boolean first = true;
		for (Entry<String, String> entry : params.entrySet()) {
			if (first) {
				first = false;
			} else {
				sb.append("&");
			}
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(key).append("=");
			if (StringUtils.isNotEmpty(value)) {
				try {
					sb.append(URLEncoder.encode(value, DEFAULT_CHARSET));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					LOGGER.error(url, e);
				}
			}
		}
		return sb.toString();
	}
	
	public static <K, V> String getParamString(Map map) {

        Iterator<Entry<K, V>> i  = map.entrySet().iterator();
        StringBuilder         sb = new StringBuilder();
        for (; ; ) {
            Entry<K, V> m     = i.next();
            K           key   = m.getKey();
            V           value = m.getValue();
            sb.append(key);
            sb.append('=');
            sb.append(value);
            if (!i.hasNext()) {
                return sb.toString();
            }
            sb.append('&');
        }
    }

	/**
	 * 发送json请求 ,返回请求结果
	 */
	public static String http(String url, Map<String, String> params, String method) {
		URL u = null;
		HttpURLConnection con = null;

		JSONObject json = new JSONObject();
		// 构建请求参数
		String sign = "";
		if (params != null) {
			for (Entry<String, String> e : params.entrySet()) {
				LOGGER.info(e.getKey() + "=============" + e.getValue());
				if (!e.getKey().equals("sign")) {
					json.put(e.getKey(), e.getValue());
				} else {
					sign = e.getValue();
				}

			}
		}
		// 发送请求
		try {
			u = new URL(url);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod(method);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("sign", sign);//设置头属性
			con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
//            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
			OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
			osw.write(json.toString());
			osw.flush();
			osw.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}

		// 读取返回内容
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
//        System.out.println(" User-Agent: " + con.getRequestProperty("User-Agent")); 
		json = new JSONObject();
		try {
			String returnContent = buffer.toString();
			json = JSONObject.parseObject(returnContent);
		} catch (Exception e) {
			json = new JSONObject();
			json.put("errcode", -10000);
			String str = buffer.toString();
			try {
				int index = 0;
				if (str.contains("<p class=\"title\">")) {
					str = str.substring(str.indexOf("<p class=\"title\">") + 17);
					index = str.indexOf("</p>");
					str = str.substring(0, index);
				} else if (str.contains("<p class=\"desc\">")) {
					str = str.substring(str.indexOf("<p class=\"desc\">") + 17);
					index = str.indexOf("</p>");
					str = str.substring(0, index);
				}
			} catch (Exception ee) {
				str = "系统异常";
			}
			json.put("errcode", "返回结果:" + str);
		}
		return json.toString();
	}

	/**
	 * 发送json请求 ,返回请求结果
	 */
	public static String httpJson(String url, JSONObject json, String method) {
		URL u = null;
		HttpURLConnection con = null;

		// 发送请求
		try {
			u = new URL(url);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod(method);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
			osw.write(json.toString());
			osw.flush();
			osw.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}

		// 读取返回内容
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		json = new JSONObject();
		try {
			String returnContent = buffer.toString();
			json = JSONObject.parseObject(returnContent);
		} catch (Exception e) {
			json = new JSONObject();
			json.put("errcode", -10000);
			String str = buffer.toString();
			try {
				int index = 0;
				if (str.contains("<p class=\"title\">")) {
					str = str.substring(str.indexOf("<p class=\"title\">") + 17);
					index = str.indexOf("</p>");
					str = str.substring(0, index);
				} else if (str.contains("<p class=\"desc\">")) {
					str = str.substring(str.indexOf("<p class=\"desc\">") + 17);
					index = str.indexOf("</p>");
					str = str.substring(0, index);
				}
			} catch (Exception ee) {
				str = "系统异常";
			}
			json.put("errcode", "返回结果:" + str);
		}
		return json.toString();
	}

	/**
	 * 发送json请求 ,返回请求结果
	 */
	public static String httpJson(String url, String jsonStr, String method) {
		URL u = null;
		HttpURLConnection con = null;
		JSONObject json = new JSONObject();
		// 发送请求
		try {
			u = new URL(url);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod(method);
			con.setDoOutput(true);
			con.setDoInput(true);
			con.setUseCaches(false);
			con.setRequestProperty("Content-Type", "application/json;charset=utf-8");
			OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
			osw.write(jsonStr);
			osw.flush();
			osw.close();

			StringBuffer buffer = new StringBuffer();
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
			}

			String returnContent = buffer.toString();
			LOGGER.info("returnContent:" + returnContent);
			if (StringUtils.isNotBlank(returnContent)) {
				json = JSONObject.parseObject(returnContent);
			}
		} catch (Exception e) {
			LOGGER.error("httpJson occur error." + LogExceptionStackUtil.LogExceptionStack(e));
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}
		return json.toString();
	}

	/**
	 * 充值专用
	 * 发送请求 ,返回请求结果
	 */
	public static String httpRecharge(String url, Map<String, String> params, String method) {
		URL u = null;
		HttpURLConnection con = null;

		// 构建请求参数
		StringBuffer sb = new StringBuffer();
		if (params != null) {
			for (Entry<String, String> e : params.entrySet()) {
				sb.append(e.getKey());
				sb.append("=");
				sb.append(e.getValue());
				sb.append("&");
			}
			sb.deleteCharAt(sb.length() - 1);
		}
		// 发送请求
		try {
			u = new URL(url);
			con = (HttpURLConnection) u.openConnection();
			con.setRequestMethod(method);
			con.setDoInput(true);// 允许输入
			con.setDoOutput(true);// 允许输出
			con.setUseCaches(false); // 不允许使用缓存
			con.setInstanceFollowRedirects(true);
			con.setRequestProperty("accept", "*/*");
			con.setRequestProperty("connection", "Keep-Alive");
			con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "utf-8");
			osw.write(sb.toString());
			osw.flush();
			osw.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (con != null) {
				con.disconnect();
			}
		}

		// 读取返回内容
		StringBuffer buffer = new StringBuffer();
		try {
			BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
			String temp;
			while ((temp = br.readLine()) != null) {
				buffer.append(temp);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		try {
			return buffer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 参数 str 手机号码
	 * urlString 链接
	 * 查询手机归属地
	 */
	public static JSONObject getMobileAddress(String urlString, String str) {
		StringBuffer sb = new StringBuffer();
		BufferedReader buffer;
		JSONObject json = new JSONObject();
		try {
			URL url = new URL(urlString + "?tel=" + str);
			//获取URL地址中的页面内容
			InputStream in = url.openStream();
			// 解决乱码问题
			buffer = new BufferedReader(new InputStreamReader(in, "gb2312"));
			String line = null;
			//一行一行的读取数据
			while ((line = buffer.readLine()) != null) {
				sb.append(line);
			}
			in.close();
			buffer.close();
			String result = sb.toString().substring(sb.toString().indexOf("=") + 1);
			json = JSON.parseObject(result);
			return json;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String doPost(String url) {

		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
		httpPost.setConfig(requestConfig);
		httpPost.setHeader("Content-type", "application/json");
		httpPost.setHeader("DataEncoding", "UTF-8");


		CloseableHttpResponse httpResponse = null;
		try {
//			httpPost.setEntity(new StringEntity(jsonStr));
			httpResponse = httpClient.execute(httpPost);
			HttpEntity entity = httpResponse.getEntity();
			String result = EntityUtils.toString(entity);
			return result;
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (httpResponse != null) {
				try {
					httpResponse.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (null != httpClient) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}





	public static void main(String[] args) throws IOException {
//		String url = "s";
//		String year = "2019";
//		String quarter = "1";
//		String month = "";
//		String day = "";
//		String day2 = "";
//		String reportType = "quarter";
//		String client = "";
//		String limit = "100000";
//		String Page = "1";
//		String paramentStr = "year=" + year + "&quarter=" + quarter
//				+ "&month=" + month + "&day=" + day + "&day2=" + day2
//				+ "&reportType=" + reportType + "&client=" + client + "&limit=" + limit
//				+ "&Page=" + Page;
//		try {
//			String res = HttpKit.Post(paramentStr, url);
//			System.out.println(res);
//		} catch (Exception e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		String     result     = HttpKit.doPost( "http://wx.palmnest.com/super_cloud/api/wechat/front/message/customMessageByUserIds?orgId=615&userIds=55716&content=kkkkk");
//		JSONObject jsonObject = JSONObject.parseObject(result);
//
//		 BigDecimal a=new BigDecimal("3");
//	        BigDecimal b=a.divide(new BigDecimal("2"),2,BigDecimal.ROUND_HALF_UP);
//	        System.out.println(b);
//
//
//
//
//
//		CloseableHttpClient client = HttpClients.createDefault();    //创建一个http客户端
//
//		HttpPost httpPost = new HttpPost(result);// 通过httpPost方式来实现我们的get请求
//
//		httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36");//伪装成浏览器请求
//
//		CloseableHttpResponse Response = client.execute(httpPost);  // 通过client调用execute方法，得到我们的执行结果就是一个response，所有的数据都封装在response里面了
//
//
//		//-----------------------------------------------------------------------
//
//
//		System.out.println(Response.getStatusLine());  //HTTP/1.1 200 OK
//
//		System.out.println(Response.getProtocolVersion());  //HTTP/1.1
//
//		System.out.println(Response.getStatusLine().getStatusCode());  //200
//
//
//		//-----------------------------------------------------------------------
//
//
//
//		HttpEntity httpEntity = Response.getEntity();         //获取某个固定的响应头
//
//		System.out.println(httpEntity.getContentType()); //Content-Type: text/html
//
//
//
//
//
//		//-----------------------------------------------------------------------
//
//
//		System.out.println(Response.getFirstHeader("Content-Type"));//Content-Type: text/html
//		System.out.println(Response.getFirstHeader("Date"));   //Date: Sun, 03 May 2020 06:58:16 GMT
//
//		//-----------------------------------------------------------------------
//
//		Header[] headers = Response.getAllHeaders();    //获取所有响应头
//		for (Header header : headers)
//		{
//			System.out.println("Key : " + header.getName()+",         ," +" Value : " + header.getValue());
//		}
		
		
		String url="http://wx.palmnest.com/super_cloud/api/wechat/front/message/customMessageByUserIdsJson";
		Integer [] arr={51156,55716};
		Map<String,Object> map=new HashMap<String, Object>();
		map.put("orgId", 615);
		map.put("userIds", arr);
		map.put("content", "测试内容");
		map.put("url", "//wx.palmnest.com/avicfile/super_wechat/noticeDetail/index.html?type=APP_NIOTICE_AUDIT&id=936&hideButton=1&sourceType=1");
        String   result  = HttpKit.HttpClientPost( JSON.toJSONString(map),url);
        System.out.println(result);


	}
}

/**
 * 证书管理
 */
class MyX509TrustManager implements X509TrustManager {

	public X509Certificate[] getAcceptedIssuers() {
		return null;
	}

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType)
			throws CertificateException {
	}
}