package com.zehong.common.utils.http;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpClientUtils {

    /**
     * get请求
     * @param url 请求地址
     * @param param 请求参数
     * @headData headData 请求头
     * @return String
     */
    public static String doGet(String url, Map<String, Object> param, Map<String, Object> headData) throws URISyntaxException, IOException {
        //创建默认的httpclient实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //响应对象
        CloseableHttpResponse response = null;
        //返回结果
        String resultStr = "";
        try {
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, String.valueOf(param.get(key)));
                }
            }
            URI uri = builder.build();
            HttpGet httpGet = new HttpGet(uri);
            //携带head数据
            if (headData != null && headData.size() > 0) {
                for (String key : headData.keySet()) {
                    httpGet.setHeader(key, (String) headData.get(key));
                }
            }
            response = httpClient.execute(httpGet);

            if (response!=null && response.getStatusLine().getStatusCode() == 200){
                HttpEntity httpEntity = response.getEntity();
                resultStr = EntityUtils.toString(httpEntity,"UTF-8");
            }
        }finally {
            close(response,httpClient);
        }
        return resultStr;
    }


    /**
     * post请求
     * @param url 请求地址
     * @param param 请求参数
     * @param headData 请求头
     * @return String
     * @throws IOException 异常信息
     */
    public static String doPost(String url, Map<String, Object> param, Map<String, Object> headData) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            if (param != null) {
                List<NameValuePair> formParams = new ArrayList<>();
                for (String key : param.keySet()) {
                    formParams.add(new BasicNameValuePair(key, String.valueOf(param.get(key))));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,"UTF-8");
                httpPost.setEntity(entity);
            }
            //携带head数据
            if (headData != null && headData.size() > 0) {
                for (String key : headData.keySet()) {
                    httpPost.setHeader(key, (String) headData.get(key));
                }
            }
            //执行post请求
            response = httpClient.execute(httpPost);
            if (response!=null && response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }finally {
            close(response,httpClient);
        }

        return resultString;
    }

    /**
     * body传参
     * @param url 请求地址
     * @param param body参数
     * @param headData 请求头
     * @return String
     * @throws IOException 异常
     */
    public static String doPost(String url,String param,Map<String, Object> headData) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            HttpPost httpPost = new HttpPost(url);
            if (param != null) {
                httpPost.setEntity(new StringEntity(param, ContentType.create("application/json", "utf-8")));
            }
            //携带head数据
            if (headData != null && headData.size() > 0) {
                for (String key : headData.keySet()) {
                    httpPost.setHeader(key, (String) headData.get(key));
                }
            }
            //执行post请求
            response = httpClient.execute(httpPost);
            if (response!=null && response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        }finally {
            close(response,httpClient);
        }

        return resultString;
    }



    /**
     * 关闭客户端
     * @param response 返回实体
     * @param httpClient 客户端
     * @throws IOException 异常信息
     */
    private static void close( CloseableHttpResponse response,CloseableHttpClient httpClient) throws IOException {
        if (response != null) {
            response.close();
        }
        httpClient.close();
    }


    public static String uploadFile (String url,HttpEntity entity) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 路径自定义
            HttpPost httpPost = new HttpPost(url);

            httpPost.setEntity(entity);
            // 执行提交
            response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                // 将响应内容转换为字符串
                result = EntityUtils.toString(responseEntity, Charset.forName("UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(response,httpClient);
        }
        return result;
    }
}
