欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

HttpClient发送请求公共方法

程序员文章站 2022-03-07 13:27:42
...
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.inspur.inserver.util.exception.MyException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static com.inspur.inserver.util.constant.SystemConstant.COMMON_CHARSET;public class HttpUtils {

    private HttpUtils(){}

    /**
     * get
     *
     *
     * @param headers
* @param querys
* @return
* @throws Exception
     */
public static HttpResponse doGet(String url,
                                     Map<String, String> headers,
                                     Map<String, String> querys)
            throws IOException {
        HttpClient httpClient = sslClient();
        HttpGet request = new HttpGet(buildUrl(url, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        return httpClient.execute(request);
    }

    /**
     * post form
     *
     *
     * @param headers
* @param querys
* @param bodys
* @return
* @throws Exception
     */
public static HttpResponse doPost(String url,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      Map<String, String> bodys)
            throws IOException {
        HttpClient httpClient = sslClient();
        HttpPost request = new HttpPost(buildUrl(url, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, COMMON_CHARSET.getValue());
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }
        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     *
     * @param headers
* @param querys
* @param body
* @return
* @throws Exception
     */
public static HttpResponse doPost(String url,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      String body) throws IOException {
        HttpClient httpClient = sslClient();
        HttpPost request = new HttpPost(buildUrl(url, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, COMMON_CHARSET.getValue()));
        }
        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     *
     * @param headers
* @param querys
* @param body
* @return
* @throws Exception
     */
public static HttpResponse doPost(String url,
                                      Map<String, String> headers,
                                      Map<String, String> querys,
                                      byte[] body)
            throws IOException {
        HttpClient httpClient = sslClient();
        HttpPost request = new HttpPost(buildUrl(url, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
    }

    /**
     * Put String
     *
     *
     * @param headers
* @param querys
* @param body
* @return
* @throws Exception
     */
public static HttpResponse doPut(String url,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     String body)
            throws IOException {
        HttpClient httpClient = sslClient();
        HttpPut request = new HttpPut(buildUrl(url, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }
        return httpClient.execute(request);
    }

    /**
     * Put stream
     *
     *
     * @param headers
* @param querys
* @param body
* @return
* @throws Exception
     */
public static HttpResponse doPut(String url,
                                     Map<String, String> headers,
                                     Map<String, String> querys,
                                     byte[] body)
            throws IOException {
        HttpClient httpClient = sslClient();
        HttpPut request = new HttpPut(buildUrl(url, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }
        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     *
     * @param headers
* @param querys
* @return
* @throws Exception
     */
public static HttpResponse doDelete(String url,
                                        Map<String, String> headers,
                                        Map<String, String> querys)
            throws IOException {
        HttpClient httpClient = sslClient();
        HttpDelete request = new HttpDelete(buildUrl(url, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }
        return httpClient.execute(request);
    }

    /**
     * 构建请求的 url
     *
     */
private static String buildUrl(String url, Map<String, String> querys) throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        if (StringUtils.isBlank(url)) {
            throw new MyException("URL is null !");
        }
        sbUrl.append(url);
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        return sbUrl.toString();
    }

    /**
     * 在调用SSL之前需要重写验证方法,取消检测SSL
     * 创建ConnectionManager,添加Connection配置信息
*
     * @return HttpClient 支持https
     */
private static HttpClient sslClient() {
        return HttpsClientUtil.getHttpsClient();
    }

    /**
     * 将结果转换成JSONObject
     *
     * @param httpResponse
* @return
* @throws IOException
     */
public static JSONObject getJson(HttpResponse httpResponse) throws IOException {
        HttpEntity entity = httpResponse.getEntity();
        String resp = EntityUtils.toString(entity, "UTF-8");
        EntityUtils.consume(entity);
        return JSON.parseObject(resp);
    }
}