package com.community.commom.utils;

import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 *　外部接口调用处理(HTTP方式)
 * Created by wuxuewen on 2016/11/8.
 */
public class HttpClientUtils {

    public static final Logger log = LoggerFactory.getLogger(HttpClientUtils.class);

    public static final String HTTP_STATUS = "200";

    /**
     * 外部HTTP接口调用处理
     *
     * @param url               接口地址
     * @param message           发送消息信息
     * @param readTimeout       发送超时时间
     * @param connectionTimeout 连接超时时间
     * @return 接口返回
     */
    public static String sendMessage(final String url, final String message, final int readTimeout, final int connectionTimeout) {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
        client.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);
        PostMethod httpPost = new PostMethod(url);
        httpPost.setRequestHeader("Response-Type", "xml");
        httpPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        RequestEntity requestXml = null;
        try {
            requestXml = new StringRequestEntity(message, "text/xml", "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        try {
            httpPost.setRequestEntity(requestXml);
            int statusCode = client.executeMethod(httpPost);
            if (statusCode == 200) {
                return httpPost.getResponseBodyAsString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
            client.getHttpConnectionManager().closeIdleConnections(0);
        }
        return null;
    }

    /**
     * HTTP GET请求调用
     *
     * @param url               请求地址
     * @param readTimeout       请求超时
     * @param connectionTimeout 连接超时
     * @return 请求返回
     */
    public static String httpGet(final String url, final int readTimeout, final int connectionTimeout) {
        String responseBody = null;
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeout);
        client.getHttpConnectionManager().getParams().setSoTimeout(readTimeout);
        GetMethod httpPost = new GetMethod(url);
        try {
            httpPost.setRequestHeader("Connection", "close");
            client.executeMethod(httpPost);
            InputStream in = httpPost.getResponseBodyAsStream();
            if (in != null) {
                BufferedReader buffer = new BufferedReader(new InputStreamReader(in, "UTF-8"));
                StringBuffer sbf;
                sbf = new StringBuffer();
                String line;
                while ((line = buffer.readLine()) != null) {
                    sbf.append(line);
                }
                buffer.close();
                responseBody = sbf.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpPost.releaseConnection();
            client.getHttpConnectionManager().closeIdleConnections(0);
        }
        return responseBody;
    }


    /**
     * 共用HTTPPOST请求处理
     *
     * @param url    请求地址
     * @param params 请求的参数信息
     * @return 返回
     * @throws Exception
     */
    public static Map<String, String> httpPost(String url, Map<String, Object> params) throws Exception {
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(2000);
        client.getHttpConnectionManager().getParams().setSoTimeout(3000);
        PostMethod httpPost = new PostMethod(url);
        Map<String, String> returnMap = new HashMap<String, String>();
        try {
            httpPost.setRequestHeader("Connection", "close");
            if (params != null) {
                for (Object o : params.entrySet()) {
                    Map.Entry entry = (Map.Entry) o;
                    Object key = entry.getKey();
                    String value = (String) entry.getValue();
                    if (StringUtils.hasText(value))
                        httpPost.addParameter(key.toString(), value);
                }
            }
            httpPost.getParams().setContentCharset("UTF-8");
            httpPost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            int statusCode = client.executeMethod(httpPost);
            log.info("Request for method " + Thread.currentThread().getStackTrace()[3].getMethodName() +
                    " statusCode=" + statusCode);
            returnMap.put("statusCode", String.valueOf(statusCode));
            String responseString = httpPost.getResponseBodyAsString();
            log.info("Response responseString " + responseString);
            returnMap.put("responseString", responseString);
        } catch (Exception e) {
            log.error("request url " + url + " Error:{}", e);
            returnMap.put("statusCode", "-1");
        } finally {
            httpPost.releaseConnection();
            client.getHttpConnectionManager().closeIdleConnections(0);
        }
        return returnMap;
    }
}
