package com.ym.mec.collectfee.utils;

import com.thoughtworks.xstream.XStream;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
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.apache.tomcat.util.http.fileupload.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

public class HttpUtil {

	public static String postXmlData(String xmlData, String url)
			throws Exception {
		OutputStreamWriter osw;
		//获取http连接
		HttpURLConnection con = getConnection(url);
		byte[] xmlByteData = xmlData.getBytes("utf-8");
		try {
			//设置Context-Length
			con.setRequestProperty("Context-Length", String.valueOf(xmlByteData.length));
			//获得输出流
			OutputStream outputStream = con.getOutputStream();
			BufferedOutputStream bos = new BufferedOutputStream(outputStream);
			osw = new OutputStreamWriter(bos, "UTF-8");
			//写入
			osw.write(xmlData);
			//清空缓存
			osw.flush();
			osw.close();
			//解析返回报文

			StringBuffer out = new StringBuffer();
			byte[] b = new byte[4096];
			for (int n; (n = con.getInputStream().read(b)) != -1;) {
				out.append(new String(b, 0, n));
			}
			return out.toString();
		} catch (IOException ex) {
			throw new IOException(ex.getMessage());
		} catch (IllegalArgumentException argumetEx) {
			throw new IllegalArgumentException(argumetEx.getMessage());
		} catch (Exception ex) {
			throw new Exception(ex.getMessage());
		}
	}
	/**
	 * 得到一个有效的连接
	 * @param url 连接端口
	 * @return HttpURLConnection 一个有效的连接
	 */
	public static HttpURLConnection getConnection(String url) throws IOException {

		HttpURLConnection urlconnection = null;
		try {
			//得到url连接对象
			URL urlcon = new URL(url);
			//获取到connection连接对象
			urlconnection = (HttpURLConnection) urlcon.openConnection();
			//设置头参数
//			urlconnection.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
			urlconnection.addRequestProperty("content-type", "application/x-www-form-urlencoded;charset=UTF-8");
//			urlconnection.setRequestProperty("Accept", "text/xml");
			urlconnection.setRequestProperty("version", "100");
			urlconnection.setRequestMethod("POST");
			urlconnection.setDoOutput(true);
			urlconnection.setDoInput(true);
			urlconnection.setUseCaches(false);
		} catch (java.net.ProtocolException proEx) {
			throw new IOException(proEx.getMessage());
		} catch (MalformedURLException MaEx) {
			throw new IOException(MaEx.getMessage());
		} catch (Exception ex) {
			throw new IOException(ex.getMessage());
		}
		//返回连接
		return urlconnection;
	}


	/**
	 * POST请求http url
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 * @throws IOException 
	 */
	public static String postForHttp(String url, Map<String, Object> parameterMap) throws IOException {
		String result = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (parameterMap != null) {
				for (Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity, "UTF-8");
			EntityUtils.consume(httpEntity);
		} finally {
			httpPost.releaseConnection();
			httpClient.close();
		}
		return result;
	}

	/**
	 * POST请求https url
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 * @throws IOException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws KeyStoreException 
	 */
	public static String postForHttps(String url, Map<String, Object> parameterMap) throws IOException, NoSuchAlgorithmException, KeyManagementException,
			KeyStoreException {
		String result = null;
		CloseableHttpClient httpClient = SimpleHttpsClient.getInstance();

		HttpPost httpPost = new HttpPost(url);
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (parameterMap != null) {
				for (Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity, "UTF-8");
			EntityUtils.consume(httpEntity);
		} finally {
			httpPost.releaseConnection();
			httpClient.close();
		}
		return result;
	}

	/**
	 * POST请求https url
	 * 
	 * @param url
	 *            URL
	 * @param json
	 *            请求参数
	 * @param headers
	 *            请求头参数
	 * @return 返回结果
	 * @throws IOException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws KeyStoreException 
	 */
	public static String postForHttps(String url, String json, Map<String, String> headers) throws IOException, NoSuchAlgorithmException,
			KeyManagementException, KeyStoreException {
		String result = null;
		CloseableHttpClient httpClient = SimpleHttpsClient.getInstance();

		HttpPost httpPost = new HttpPost(url);
		if (headers != null && headers.size() > 0) {
			for (Entry<String, String> entry : headers.entrySet()) {
				httpPost.setHeader(entry.getKey(), entry.getValue());
			}
		}
		try {
			httpPost.setEntity(new StringEntity(json, "UTF-8"));

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity, "UTF-8");
			EntityUtils.consume(httpEntity);
		} finally {
			httpPost.releaseConnection();
			httpClient.close();
		}
		return result;
	}

	/**
	 * GET请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 * @throws IOException 
	 */
	public static String get(String url, Map<String, Object> parameterMap) throws IOException {
		return get(url, parameterMap, null);
	}

	/**
	 * GET请求
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @param headers
	 *            请求头
	 * @return 返回结果
	 * @throws IOException 
	 */
	public static String get(String url, Map<String, Object> parameterMap, Map<String, String> headers) throws IOException {
		String result = null;
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpGet httpGet = null;
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (parameterMap != null) {
				for (Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			httpGet = new HttpGet(url + (StringUtils.contains(url, "?") ? "&" : "?") + EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs, "UTF-8")));
			if (headers != null && headers.size() > 0) {
				for (Entry<String, String> entry : headers.entrySet()) {
					httpGet.setHeader(entry.getKey(), entry.getValue());
				}
			}
			HttpResponse httpResponse = httpClient.execute(httpGet);
			HttpEntity httpEntity = httpResponse.getEntity();
			result = EntityUtils.toString(httpEntity, "UTF-8");
			EntityUtils.consume(httpEntity);
		} finally {
			if (httpGet != null) {
				httpGet.releaseConnection();
			}
			httpClient.close();
		}
		return result;
	}

	/**
	 * POST请求https url
	 * 
	 * @param url
	 *            URL
	 * @param parameterMap
	 *            请求参数
	 * @return 返回结果
	 * @throws IOException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 * @throws KeyStoreException 
	 */
	public static boolean downLoadPostForHttps(String url, Map<String, String> headerMap, Map<String, Object> parameterMap, String filePath)
			throws IOException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
		CloseableHttpClient httpClient = HttpClients.createDefault();

		HttpPost httpPost = new HttpPost(url);
		if (headerMap != null) {
			for (Entry<String, String> entry : headerMap.entrySet()) {
				httpPost.addHeader(entry.getKey(), entry.getValue());
			}
		}
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			if (parameterMap != null) {
				for (Entry<String, Object> entry : parameterMap.entrySet()) {
					String name = entry.getKey();
					String value = ConvertUtils.convert(entry.getValue());
					if (StringUtils.isNotEmpty(name)) {
						nameValuePairs.add(new BasicNameValuePair(name, value));
					}
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream is = httpEntity.getContent();

			File file = new File(filePath);
			file.getParentFile().mkdirs();

			FileOutputStream fileout = new FileOutputStream(file);

			IOUtils.copy(is, fileout);
			is.close();
			fileout.flush();
			fileout.close();

			EntityUtils.consume(httpEntity);
		} finally {
			httpPost.releaseConnection();
			httpClient.close();
		}
		return true;
	}
}
