HttpClient封装工具类

 

 

 1 URIBuilder ub = new URIBuilder();
 2         URI uri = ub.setScheme("http")
 3                 .setHost("www.google.com")
 4                 .setPath("/search")
 5                 .setParameter("q", "编程狗的博客")
 6                 .setParameter("btnG", "Google Search")
 7                 .setParameter("aq", "f")
 8                 .setParameter("oq", "")
 9                 .build();
10         System.out.println(uri);

 

 

HttpClient封装工具类
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>  
Mven依赖

 

HttpClient封装工具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Map;



public final class HttpClientUtils {

    private static volatile PoolingHttpClientConnectionManager cm;// 连接池配置管理

    private static String EMPTY_STR = "";

    private static String UTF_8 = "UTF-8";

    /**
     * 配置初始化
     */
    private static synchronized void init() {
        if (cm == null) {
            cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(50);// 整个连接池最大连接数
            cm.setDefaultMaxPerRoute(25);// 每路由最大连接数,默认值是2
        }
    }

    /**
     * 通过连接池获取HttpClient
     */
    private static CloseableHttpClient getHttpClient() {
        // 初始化
        init();
        // 返回httpclient
        return HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * get请求
     */
    public static HttpEntity httpGetRequest(String url) throws URISyntaxException, IOException {

        return httpGetRequest(url,null,null);
    }

    /**
     * get请求,参数
     */
    public static HttpEntity httpGetRequest(String url, Map<String, Object> params) throws URISyntaxException, IOException {

        return httpGetRequest(url,null,params);
    }


    /**
     * get请求,请求头
     */
    public static HttpEntity httpGetRequest(String url, HashMap<String, Object> headers) throws URISyntaxException, IOException {

        return httpGetRequest(url,headers,null);
    }


    /**
     * get请求,请求头 + 参数
     */
    public static HttpEntity httpGetRequest(String url, Map<String, Object> headers, Map<String, Object> params) throws URISyntaxException, IOException {
        URIBuilder ub = new URIBuilder(url);

        if(!Objects.isNull(params)){
            ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
            ub.setParameters(pairs);
        }

        HttpGet httpGet = new HttpGet(ub.build());
        if(!Objects.isNull(headers)){
            for (Map.Entry<String, Object> header : headers.entrySet()) {
                httpGet.addHeader(header.getKey(), String.valueOf(header.getValue()));
            }
        }

        return getEntity(httpGet);
    }


    /**
     * post请求
     */
    public static HttpEntity httpPostRequest(String url) throws IOException {
        return httpPostRequest(url, null, null, null);
    }

    /**
     * post请求,请求头
     */
    public static HttpEntity httpPostRequest(String url, HashMap<String, Object> headers) throws IOException {
        return httpPostRequest(url, headers, null, null);
    }

    /**
     * post请求,json体
     */
    public static HttpEntity httpPostRequest(String url, String jsonStrBody) throws IOException {
        return httpPostRequest(url, null, null, jsonStrBody);
    }


    /**
     * post请求,formdata参数
     */
    public static HttpEntity httpPostRequest(String url, Map<String, Object> params) throws IOException {
        return httpPostRequest(url, null, params, null);
    }

    /**
     * post请求,请求头 + json体
     */
    public static HttpEntity httpPostRequest(String url, HashMap<String, Object> headers, String jsonStrBody) throws IOException {
        return httpPostRequest(url, headers, null, jsonStrBody);
    }


    /**
     * post请求,请求头 + formdata参数
     */
    public static HttpEntity httpPostRequest(String url, HashMap<String, Object> headers, Map<String, Object> params) throws IOException {
        return httpPostRequest(url, headers, params, null);
    }


    /**
     * post请求汇总方法:请求头,formdata参数,jsonbody参数
     */
    private static HttpEntity httpPostRequest(String url, Map<String, Object> headers, Map<String, Object> params, String jsonStrBody) throws IOException {
        HttpPost httpPost = new HttpPost(url);

        if(!Objects.isNull(headers)){
            for (Map.Entry<String, Object> param : headers.entrySet()) {
                httpPost.addHeader(param.getKey(), String.valueOf(param.getValue()));
            }
        }
        if (!Objects.isNull(params)){
            ArrayList<NameValuePair> pairs = covertParams2NVPS(params);
            httpPost.setEntity(new UrlEncodedFormEntity(pairs, UTF_8));
        }
        if(!Objects.isNull(jsonStrBody)){
            StringEntity se = new StringEntity(jsonStrBody, UTF_8);
            se.setContentType("text/json");
            httpPost.setEntity(se);
        }
        return getEntity(httpPost);
    }

    /**
     * 处理http请求,获取HttpEntity
     */
    private static HttpEntity getEntity(HttpRequestBase request) throws IOException {
        CloseableHttpClient httpClient = getHttpClient();
        CloseableHttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            request.abort();
        }
        HttpEntity entity = response.getEntity();
//        response.close();
//        httpClient.close();
        return entity;
    }


    /**
     * 处理Http请求,获取String结果
     */
    public static String getResultOfString(HttpEntity httpEntity) throws IOException {
        String result = EntityUtils.toString(httpEntity, UTF_8);
        return result;
    }

    /**
     * 处理Http请求,获取JSONObject结果
     */
    public static JSONObject getResultOfJSONObject(HttpEntity httpEntity) throws IOException {
        String result = EntityUtils.toString(httpEntity, UTF_8);
        result = StringEscapeUtils.unescapeJava(result);
        JSONObject jsonObject = JSON.parseObject(result);
        return jsonObject;
    }


    /**
     * 转换成http参数对
     *
     * @param params
     * @return
     */
    private static ArrayList<NameValuePair> covertParams2NVPS(Map<String, Object> params) {
        ArrayList<NameValuePair> pairs = new ArrayList<>();
        for (Map.Entry<String, Object> param : params.entrySet()) {
            pairs.add(new BasicNameValuePair(param.getKey(), String.valueOf(param.getValue())));
        }
        return pairs;
    }
}
HttClient工具类

 

上一篇:[每日一题] [力扣 437] [leetcode 437] 路径总和III 2021.9.28


下一篇:*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ViewController > setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key