package com.ads.common.http;

import com.ads.common.data.HttpJson;
import com.ads.common.util.UtilMessage;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
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.HttpClients;
import org.apache.http.util.EntityUtils;
import java.util.Map;

/**
 * HttpClient远程访问
 * @author wuyifeng
 * @date 2020/8/6
 */
public class HttpClientUtil {
    private static final int TIME_OUT = 30 * 1000;// 单位毫秒

    /**
     * GET请求
     */
    public static HttpJson doGet(String url) {
        HttpJson httpJson = new HttpJson();
        HttpClient httpclient = HttpClients.createDefault();
        try {
            HttpGet httpget = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpget);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                /* 读返回数据 */
                String conResult = EntityUtils.toString(response.getEntity());
                httpJson.setSuccess(true);
                httpJson.setMsg(conResult);
            } else {
                httpJson.setMsg(UtilMessage.HTTP_ERROR + ";接口地址:" + url);
            }
        } catch (Exception e) {
            httpJson.setMsg(UtilMessage.HTTP_ERROR);
        }
        return httpJson;
    }


    /**
     * post请求
     */
    public static HttpJson httpPost(String url, Map<String, Object> inMap) {
        HttpJson httpJson = new HttpJson();
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(TIME_OUT).setConnectionRequestTimeout(TIME_OUT).setSocketTimeout(TIME_OUT).build();
        httppost.setConfig(requestConfig);

        try {
            // 把数据改为String格式
            String stringObj = JSONObject.toJSONString(inMap);
            httppost.addHeader("Content-Type", "application/json");
            httppost.setEntity(new StringEntity(stringObj, "UTF-8"));
            HttpResponse response = httpclient.execute(httppost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                /* 读返回数据 */
                String conResult = EntityUtils.toString(response.getEntity(), "GBK");
                httpJson.setSuccess(true);
                httpJson.setMsg(conResult);
            } else {
                httpJson.setMsg(UtilMessage.HTTP_ERROR + ";接口地址:" + url);
            }

        } catch (Exception e) {
            httpJson.setMsg(UtilMessage.HTTP_ERROR);
        }

        return httpJson;
    }

}
