package com.saye.hospitalgd.util;

import java.io.IOException;
import java.net.ConnectException;
import java.util.*;
import java.util.Map.Entry;

import com.alibaba.fastjson.JSON;
import com.saye.hospitalgd.commons.string.StringDUtil;
import com.saye.hospitalgd.util.pojo.HttpResult;
import org.apache.http.*;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;



public class HttpDutil {


	/**
	 * @description 发送POST(JSON)请求
	 * @author mczheng       
	 * @created 2018-10-17 下午6:16:15 
	 * @param requestUrl
	 * @param requestHeaderMap
	 * @param requestData
	 * @return
	 */
	public static HttpResult sendPostJSONRequest(String requestUrl, HashMap<String, String> requestHeaderMap, String requestData) {
		
		HttpResult httpResult = new HttpResult();
		String errCode = "0";
		String errMsg = "";
		int statusCode = -1;
		String responseData = "";
		HashMap<Object, Object> resHeaderMap = new HashMap<Object, Object>();

		DefaultHttpClient httpClient = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(requestUrl);
		httpPost.setHeader("content-type", "application/json;utf-8");		
	    if(null != requestHeaderMap) {
	    	Iterator iterator = requestHeaderMap.entrySet().iterator();
	    	while(iterator.hasNext()) {
	    		Entry<String, String> entry = (Entry<String, String>) iterator.next();
	    		httpPost.setHeader(entry.getKey(), entry.getValue());
	    	}
	    }
	    try {
			StringEntity strEntity;
			strEntity = new StringEntity(requestData,"UTF-8");
			httpPost.setEntity(strEntity);
			HttpResponse response = httpClient.execute(httpPost);
			statusCode = response.getStatusLine().getStatusCode();
			HttpEntity resEntity = (HttpEntity) response.getEntity();
			if (resEntity != null) {
				responseData = EntityUtils.toString(resEntity, "UTF-8");
				Header[] headers = response.getAllHeaders();
				if(null != headers) {
					for (Header header : headers) {
						String name = header.getName();
						String value = header.getValue();
						resHeaderMap.put(name, value);
					}
				}
			}
		} catch (ConnectException ce) {
			errCode = "001";
			errMsg = "连接超时：" + ce.getLocalizedMessage();
		} catch (Exception e) {
			errCode = "002";
			errMsg = "请求异常：" + e.getLocalizedMessage();
		}
	    httpResult.setErrCode(errCode);
	    httpResult.setErrMsg(errMsg);
	    httpResult.setStatusCode(statusCode);
	    httpResult.setResponseData(responseData);
	    httpResult.setResHeaderMap(resHeaderMap);
		return httpResult;
	}


	public static String post(String url, HashMap<Object, Object> pramMap) throws Exception {
		String result = null;
		// DefaultHttpClient已过时,使用CloseableHttpClient替代
		CloseableHttpClient closeableHttpClient = null;
		CloseableHttpResponse response = null;
		try {
			closeableHttpClient = HttpClients.createDefault();
			HttpPost postRequest = new HttpPost(url);
			postRequest.setHeader("content-type", "application/json;utf-8");

			String s1 = JSON.toJSONString(pramMap);
			StringEntity s = new StringEntity(s1,"UTF-8");
			s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
			postRequest.setEntity(s);

			response = closeableHttpClient.execute(postRequest);
			if(response!=null && response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
				result = EntityUtils.toString(response.getEntity(), "utf-8");
			}else{
				throw new Exception("post请求失败,url:" + url);
			}

		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			try {
				if(response != null){
					response.close();
				}
				if(closeableHttpClient != null){
					closeableHttpClient.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return result;
	}


}
