package shop.alien.util.httpsend.apache;

import com.alibaba.fastjson2.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * Get请求
 *
 * @author ssk
 * @version 1.0
 * @date 2020/4/22 10:37
 */
public class HttpGetRequestUtil {
    public static void main(String[] args) {
        //请求参数
        Map<String, String> map = new HashMap<>();
//        map.put("app_id", "ej6plljgwnwcvl8u");
//        map.put("app_secret", "UUUrYjhCL3RLQjFpZlBBbGd3cHFKZz09");
//        String result = getRequest(map, "https://www.mxnzp.com/api/holiday/single/20200422");

//        map.put("msgtype", "text");
//        map.put("text", "");
        Map<String, String> headerMap = new HashMap<>();
//        String url = "https://oapi.dingtalk.com/robot/send?access_token=8c90fb3b08a0126d0181faf1cd7597fb5eae078a522b59de28b0882575eb4196";
        String url = "https://geoapi.qweather.com/v2/city/lookup";
        map.put("location", "大连");
        map.put("key", "109ef16ad7a6448bbf3e670fa38792fa");
        String result = getRequest(url, map, headerMap);
        System.out.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        System.out.println(jsonObject);
    }

    /**
     * Get请求
     *
     * @param url       请求url
     * @param paramMap  请求参数
     * @param headerMap 请求头
     * @return 返回结果
     */
    public static String getRequest(String url, Map<String, String> paramMap, Map<String, String> headerMap) {
        String result = "";
        HttpGet get = new HttpGet(url);
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();
            List<NameValuePair> params = setHttpParams(paramMap);
            String param = URLEncodedUtils.format(params, StandardCharsets.UTF_8);
            get.setURI(URI.create(url + "?" + param));
            //设置Header
            if (headerMap.size() > 0) {
                Set<String> set = headerMap.keySet();
                for (String next : set) {
                    get.setHeader(next, headerMap.get(next));
                }
            }
            HttpResponse response = httpClient.execute(get);
            result = getHttpEntityContent(response);
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "服务器异常";
            }
        } catch (Exception e) {
            System.out.println("请求异常");
            throw new RuntimeException(e);
        } finally {
            get.abort();
        }
        return result;
    }

    /**
     * 请求参数处理
     *
     * @param paramMap 请求参数
     * @return 处理后参数
     */
    public static List<NameValuePair> setHttpParams(Map<String, String> paramMap) {
        List<NameValuePair> params = new ArrayList<>();
        Set<Map.Entry<String, String>> set = paramMap.entrySet();
        for (Map.Entry<String, String> entry : set) {
            params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
        }
        return params;
    }

    /**
     * 请求网络
     *
     * @param response 请求内容
     * @return 返回结果
     * @throws UnsupportedOperationException
     * @throws IOException
     */
    public static String getHttpEntityContent(HttpResponse response) throws UnsupportedOperationException, IOException {
        String result = "";
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream in = entity.getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                strber.append(line + '\n');
            }
            br.close();
            in.close();
            result = strber.toString();
        }
        return result;
    }
}
