package org.fouram.core.util;

import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
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.util.EntityUtils;

public class HttpClientUtil {
	private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
			.setConnectionRequestTimeout(15000).build();
	private static CloseableHttpClient httpclient = HttpClients.createDefault();

	public static String postJson(String url, String parameters) throws IOException {
		return postBase(url, parameters, "application/json");
	}

	public static String postXml(String url, String parameters) throws IOException {
		return postBase(url, parameters, "text/xml");
	}

	public static String postBase(String url, String parameters, String contentType) throws IOException {
		// 新建Http post请求
		// 处理请求，得到响应
		CloseableHttpResponse response = null;
		String postResult = null;
		try {
			HttpPost httppost = new HttpPost(url);
			httppost.setConfig(requestConfig);
			if (StringUtils.isNotBlank(parameters)) {
				httppost.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));
			}
			httppost.addHeader("Content-type", contentType + "; charset=utf-8");
			httppost.setHeader("Accept", contentType);
			response = httpclient.execute(httppost);
			// 打印返回的结果
			HttpEntity entity = response.getEntity();
			postResult = EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			LoggerUtil.error(e);
		} finally {
			// 关闭连接,释放资源
			if (response != null) {
				response.close();
			}
		}
		return postResult;
	}
}
