package org.jeecg.modules.pay.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * http请求工具类
 *
 * @author Mr丶xie
 * @version 1.0.0
 * @mail xielinke@lklink.cn
 */
public class HttpUtil {

    /**
     * 请求工具
     **/
    public static HttpResponse post(String url, String message, String authorization) throws IOException, ClientProtocolException {
        StringEntity entity = new StringEntity(message, "UTF-8");
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("Authorization", authorization);
        headerMap.put("Accept", "application/json");
        headerMap.put("Content-Type", "application/json");
        return post(url, entity, headerMap);
    }

    /**
     * 请求工具
     **/
    public static HttpResponse post(String url, HttpEntity entity, Map<String, String> headerMap) throws IOException, ClientProtocolException {
        HttpClient http = HttpClientPool.getClient();
        HttpPost post = new HttpPost(url);
        post.setEntity(entity);
        for (String key : headerMap.keySet()) {
            post.setHeader(key, headerMap.get(key));
        }
        return http.execute(post);
    }

    /**
     * 读取响应header 数据 工具
     **/
    public static String getHeadValue(HttpResponse response, String key) {
        return (response.containsHeader(key)) ? response.getFirstHeader(key).getValue() : "";
    }
}
