常用HttpClientUtil,拿来即用

最近项目中需要调用第三方接口,于是自己写了一个HttpClientUtil,拿来即用,封装了三个常用的get请求,Post表单请求和Post Json请求方法
如有不对,欢迎指正评论
1 pom.xmll导入依赖
在这里插入图片描述
2 上代码
package com.sunpeifu.http;

import com.alibaba.fastjson.JSON;
import com.sunpeifu.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ServiceUnavailableRetryStrategy;
import org.apache.http.client.config.RequestConfig;
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.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HttpContext;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

public class HttpClientUtil {

/***
 *  编码集
 */
private final static String CHAR_SET = "UTF-8";
/***
 *  Post表单请求形式请求头
 */
private final static String CONTENT_TYPE_POST_FORM = "application/x-www-form-urlencoded";
/***
 *  Post Json请求头
 */
private final static String CONTENT_TYPE_JSON = "application/json";
/***
 *  连接管理器
 */
private static PoolingHttpClientConnectionManager poolManager;
/***
 *  请求配置
 */
private static RequestConfig requestConfig;

static {
    // 静态代码块,初始化HtppClinet连接池配置信息,同时支持http和https
    try {
        System.out.println("初始化连接池-------->>>>开始");
        // 使用SSL连接Https
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLContext sslContext = builder.build();
        // 创建SSL连接工厂
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslConnectionSocketFactory).build();
        // 初始化连接管理器
        poolManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        // 设置最大连接数
        poolManager.setMaxTotal(1000);
        // 设置最大路由
        poolManager.setDefaultMaxPerRoute(300);
        // 从连接池获取连接超时时间
        int coonectionRequestTimeOut = 5000;
        // 客户端和服务器建立连接超时时间
        int connectTimeout = 5000;
        // 客户端从服务器建立连接超时时间
        int socketTimeout = 5000;
        requestConfig = RequestConfig.custom().setConnectionRequestTimeout(coonectionRequestTimeOut)
                .setConnectTimeout(connectTimeout)
                .setSocketTimeout(socketTimeout).build();
        System.out.println("初始化连接池-------->>>>结束");

    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("初始化连接池-------->>>>失败");
    }
}


public static String doGet(String url, Map<String, String> params) {
    String result = "";
    // 获取http客户端
    // CloseableHttpClient httpClient = getCloseableHttpClient();
    // 获取http客户端从连接池中
    CloseableHttpClient httpClient = getCloseableHttpClientFromPool();
    // 响应模型
    CloseableHttpResponse httpResponse = null;
    try {
        // 创建URI 拼接请求参数
        URIBuilder uriBuilder = new URIBuilder(url);
        // uri拼接参数
        if (null != params) {
            Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> next = it.next();
                uriBuilder.addParameter(next.getKey(), next.getValue());
            }

        }
        URI uri = uriBuilder.build();
        // 创建Get请求
        HttpGet httpGet = new HttpGet(uri);
        httpResponse = httpClient.execute(httpGet);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            // 获取响应实体
            HttpEntity httpEntity = httpResponse.getEntity();
            if (null != httpEntity) {
                result = EntityUtils.toString(httpEntity, CHAR_SET);
                System.out.println("响应内容:" + result);
                return result;
            }

        }
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        System.out.println("响应码:" + statusCode);

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (null != httpResponse) {
                httpResponse.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;
}

private static CloseableHttpClient getCloseableHttpClient() {
    return HttpClientBuilder.create().build();
}

/**
 * 从http连接池中获取连接
 */
private static CloseableHttpClient getCloseableHttpClientFromPool() {
    //
    ServiceUnavailableRetryStrategy serviceUnavailableRetryStrategy = new ServiceUnavailableRetryStrategy() {
        @Override
        public boolean retryRequest(HttpResponse httpResponse, int executionCount, HttpContext httpContext) {
            if (executionCount < 3) {
                System.out.println("ServiceUnavailableRetryStrategy");
                return true;
            } else {
                return false;
            }
        }

        // 重试时间间隔
        @Override
        public long getRetryInterval() {
            return 3000L;
        }
    };


    // 设置连接池管理
    CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(poolManager)
            // 设置请求配置策略
            .setDefaultRequestConfig(requestConfig)
            // 设置重试次数
            .setRetryHandler(new DefaultHttpRequestRetryHandler()).build();
    return httpClient;

}


/**
 * Post请求,表单形式
 */
public static String doPost(String url, Map<String, String> params) {
    String result = "";
    // 获取http客户端
    CloseableHttpClient httpClient = getCloseableHttpClient();
    // 响应模型
    CloseableHttpResponse httpResponse = null;
    try {
        // Post提交封装参数列表
        ArrayList<NameValuePair> postParamsList = new ArrayList<>();
        if (null != params) {
            Iterator<Map.Entry<String, String>> it = params.entrySet().iterator();
            while (it.hasNext()) {
                Map.Entry<String, String> next = it.next();
                postParamsList.add(new BasicNameValuePair(next.getKey(), next.getValue()));
            }
        }
        // 创建Uri
        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(postParamsList, CHAR_SET);
        // 设置表达请求类型
        urlEncodedFormEntity.setContentType(CONTENT_TYPE_POST_FORM);
        HttpPost httpPost = new HttpPost(url);
        // 设置请求体
        httpPost.setEntity(urlEncodedFormEntity);
        // 执行post请求
        httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(httpResponse.getEntity(), CHAR_SET);
            System.out.println("Post form reponse {}" + result);
            return result;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            CloseResource(httpClient, httpResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}

private static void CloseResource(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) throws IOException {
    if (null != httpResponse) {
        httpResponse.close();
    }
    if (null != httpClient) {
        httpClient.close();
    }
}

/***
 *  Post请求,Json形式
 */
public static String doPostJson(String url, String jsonStr) {
    String result = "";
    CloseableHttpClient httpClient = getCloseableHttpClient();
    CloseableHttpResponse httpResponse = null;
    try {
        // 创建Post
        HttpPost httpPost = new HttpPost(url);

        // 封装请求参数
        StringEntity stringEntity = new StringEntity(jsonStr, CHAR_SET);
        // 设置请求参数封装形式
        stringEntity.setContentType(CONTENT_TYPE_JSON);
        httpPost.setEntity(stringEntity);
        httpResponse = httpClient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            result = EntityUtils.toString(httpResponse.getEntity(), CHAR_SET);
            System.out.println(result);
            return result;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            CloseResource(httpClient, httpResponse);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}

public static void main(String[] args) {
    // String getUrl = "http://127.0.0.1:8080/testHttpClientUtilGet";
    //  Map m = new HashMap();
    //  m.put("name","小明");
    // m.put("age","123");
    // String result = doGet(getUrl, m);
    // String postUrl = "http://127.0.0.1:8080/testHttpClientUtilPost";
    // String s = doPost(postUrl, m);
    String postJsonUrl = "http://127.0.0.1:8080/testHttpClientUtilPostJson";
    User user = new User();
    user.setUid("123");
    user.setUserName("小明");
    user.setAge("18");
    user.setSex("男");
    String jsonStr = JSON.toJSONString(user);
    doPostJson(postJsonUrl,jsonStr);

    // System.out.println(s);
    // System.out.println(result);
}

}

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java常用的Httpclient工具是HttpclientUtilHttpclientUtil是一个基于Apache HttpClient组件封装的工具类,它提供了简洁的接口和方法,使得Java开发者可以轻松地进行HTTP请求的发送和接收。 HttpclientUtil的主要特点和用途包括以下几个方面: 1. 发送HTTP请求:HttpclientUtil提供了get和post两种发送HTTP请求的方法,开发者可以根据需要选择合适的方法。发送请求时,可以设置请求头、请求参数、超时时间等。 2. 接收HTTP响应:HttpclientUtil能够接收HTTP响应,并对响应进行处理。开发者可以通过获取响应头、响应体等信息,实现对响应的解析和处理。 3. 支持HTTPS:HttpclientUtil对HTTPS请求也提供了支持,可以实现HTTPS请求的发送和接收。同时,也支持自定义HTTPS证书的配置,提高了安全性。 4. 连接池管理:HttpclientUtil使用连接池来管理HTTP连接,可以有效地提高请求的性能和效率。连接池可以复用已经建立的连接,减少了连接的建立和关闭的次数。 5. 支持cookie管理:HttpclientUtil能够自动管理请求和响应中的cookie信息,简化了开发者对cookie的处理过程。 6. 异步请求:HttpclientUtil支持异步请求,可以实现并发发送多个HTTP请求,并对响应进行处理。 总的来说,HttpclientUtil是一个功能强大、使用简便的Httpclient工具类,它方便了Java开发者进行HTTP请求的发送和接收,并提供了丰富的功能和选项,以满足不同的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值