package cn.com.ctop.callback.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URLEncoder;
import java.util.Map;

/**
 * @author 宋英豪
 */

public class HttpUtils {
    public static String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36";

    public static String httpGet(String url, Map<String, Object> paramsMap, Map<String, String> headers) {
        String result = null;
        try {
            // CloseableHttpClient httpClient = HttpClients.createDefault();
            //创建参数列表
            HttpClient httpclient = getHttpclient();
            StringBuilder postBody = null;
            if (paramsMap != null) {
                postBody = new StringBuilder();
                for (Map.Entry<String, Object> entry : paramsMap.entrySet()) {
                    if (entry.getValue() == null) {
                        continue;
                    }
                    postBody.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue().toString(),
                            "utf-8")).append("&");
                }
                if (!paramsMap.isEmpty()) {
                    postBody.deleteCharAt(postBody.length() - 1);
                }
            }
            String urlStr;
            if (postBody != null && postBody.length() > 0) {
                urlStr = url + "?" + postBody;
            } else {
                urlStr = url;
            }
            HttpGet httpget = new HttpGet(urlStr);
            httpget.setHeader("User-Agent", USER_AGENT);
            if (headers != null) {
                for (String key : headers.keySet()) {
                    httpget.setHeader(key, headers.get(key));
                }
            }
            HttpEntity respEntity;
            HttpResponse response = httpclient.execute(httpget);
            respEntity = response.getEntity();
            result = EntityUtils.toString(respEntity);
        } catch (Exception e) {

            e.printStackTrace();
        }
        return result;
    }

    public static HttpClient getHttpclient() {
        RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(180000).setConnectTimeout(30000)
                .setConnectionRequestTimeout(30000).setStaleConnectionCheckEnabled(true).build();
        return HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
    }

}
