HttpClient调用第三方接口 底层代码的封装 方便以后使用

这篇博客介绍了如何在Java项目中封装HttpClient工具类,用于高效调用第三方API接口。作者提供了不同请求方式的封装示例,并展示了在Service及Controller层如何使用这些工具方法获取所需数据。注意在视图解析时,需要正确使用对象属性。
摘要由CSDN通过智能技术生成

最近在做一个项目,使用的是api接口,需要使用httpClient调用第三方的接口 特意整理了一下代码 封装了httpclientUtil 方便使用
首先封装各种不同的请求方式

public class HttpClientUtil {
   

    private final static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class.getSimpleName());

    // 连接超时
    private static final int connection_timeout = 1000 * 60 * 2;
    // 指定时间内服务器端没有反应
    private static final int socket_timeout = 1000 * 40;
    // 请求超时
    private static final int request_timeout = 1000 * 40;
    // 每个主机
    private static int max_host_connections = 2000;
    // 总的连接数
    private static int max_total_connections = 5000;

    private static final String charset = "utf-8";
    // 自定义头前缀
    private static final String filter_header_prefix = "httpclient_";
    // 请求格式,默认json格式
    private static final String request_format = "httpclient_format";

    private static HttpClient httpClient = null;
    private static Set<String> excludeHeaders = new HashSet<String>();
    private static RequestConfig default_request_config = null;
    static {
        default_request_config = RequestConfig.custom().setSocketTimeout(socket_timeout).setConnectTimeout(
                connection_timeout).setConnectionRequestTimeout(request_timeout).build();

        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
        connMgr.setMaxTotal(max_total_connections);
        connMgr.setDefaultMaxPerRoute(max_host_connections);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setConnectionManager(connMgr);
        httpClientBuilder.setDefaultRequestConfig(default_request_config);

        ConnectionConfig connConfig = ConnectionConfig.custom().setCharset(Charset.forName(charset)).build();

        httpClientBuilder.setDefaultConnectionConfig(connConfig);

        httpClient = httpClientBuilder.build();
        //过滤头
        excludeHeaders.add(HTTP.CONTENT_LEN.toLowerCase());
 
以下是使用Httpclient调用第三方接口的详细代码: 1. 引入Httpclient库 首先需要在项目中引入Httpclient库,可以在Maven中添加如下依赖: ``` <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.12</version> </dependency> ``` 2. 创建HttpClient对象 ``` CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 3. 创建请求对象 ``` String url = "http://api.xxx.com/user/info"; HttpPost httpPost = new HttpPost(url); ``` 这个例子中,我们发送的请求是POST请求,URL是"http://api.xxx.com/user/info"。 4. 设置请求参数 如果发送POST请求,需要设置请求参数。我们可以创建一个List<NameValuePair>来存储参数,例如: ``` List<NameValuePair> formParams = new ArrayList<>(); formParams.add(new BasicNameValuePair("username", "test")); formParams.add(new BasicNameValuePair("password", "123456")); ``` 这个例子中,我们设置了两个参数,一个是"username",值为"test",另一个是"password",值为"123456"。 然后将参数设置到请求对象中: ``` UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8"); httpPost.setEntity(formEntity); ``` 5. 发送请求并获取响应 ``` CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); // 处理响应结果 } finally { response.close(); } ``` 首先通过httpClient的execute方法发送请求,得到响应对象response。在finally里将响应对象关闭,释放链接。 然后通过HttpEntity中的EntityUtils将响应实体entity转换成字符串类型,供后续处理。 6. 处理响应结果 得到响应结果之后,我们需要根据第三方接口的具体情况来做不同的处理。例如,如果第三方接口返回的是JSON数据,我们可以通过Jackson库将JSON字符串转换成POJO对象,例如: ``` ObjectMapper objectMapper = new ObjectMapper(); User user = objectMapper.readValue(result, User.class); ``` 这个例子中,我们将响应结果result转换成了一个User对象。 7. 完整代码 ``` import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; 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.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class HttpClientUtil { public static void main(String[] args) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); String url = "http://api.xxx.com/user/info"; HttpPost httpPost = new HttpPost(url); List<NameValuePair> formParams = new ArrayList<>(); formParams.add(new BasicNameValuePair("username", "test")); formParams.add(new BasicNameValuePair("password", "123456")); UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formParams, "UTF-8"); httpPost.setEntity(formEntity); CloseableHttpResponse response = httpClient.execute(httpPost); try { HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "UTF-8"); // 处理响应结果 ObjectMapper objectMapper = new ObjectMapper(); User user = objectMapper.readValue(result, User.class); System.out.println(user); } finally { response.close(); } } public static class User { private String username; private String password; // getter, setter } } ```
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值