HttpClient常用方法的封装

原文转载于:https://www.cnblogs.com/soul-wonder/p/9085869.html

只是在此基础上进行了改进,方便自己使用

1.引入pom文件:

<!-- springboot整合HttpClient 注意:3.X和4.0.X和4.5.X区别很大-->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.5</version>
</dependency>

2.添加HttpClient 返回统一格式


import lombok.Data;

/**
 * HttpClient 返回统一格式
 *
 */
@Data
public class HttpResult {
    // 响应的状态码
    private int code;

    // 响应的响应体
    private String body;

}

3.封装HttpClient方法


import com.alibaba.fastjson.JSON;
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.*;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 封装HttpClient常用方法
 *
 */
public class HttpClientUtil {

    //设置连接超时时间,单位毫秒。
    public final static int CONNECT_TIMEOUT = 3000;
    //设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
    public final static int CONNECT_REQUEST_TIMEOUT = 1000;
    //请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
    public final static int SOCKET_TIMEOUT = 3000;

    /**
     * 不带参数的get 表单形式
     *
     * @param uri
     * @return
     * @throws Exception
     */
    public static HttpResult doGet(String uri) throws Exception {
        return doGet(uri, null);
    }

    /**
     * 带参数的get请求 表单形式
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doGet(String url, Map<String, Object> map) throws Exception {
        // 1.创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 2.设置请求参数
        if (map != null) {
            // 遍历请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封装请求参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 3.创建请求对象httpGet
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // 4.使用httpClient发起请求
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpGet);

        // 5.解析返回结果,封装返回对象httpResult
        // 5.1获取状态码
        int code = response.getStatusLine().getStatusCode();

        // 5.2 获取响应体
        // 使用EntityUtils.toString方法必须保证entity不为空
        String body = null;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        HttpResult result = new HttpResult();
        result.setCode(code);
        result.setBody(body);
        return result;
    }

    /**
     * 不带参数的post请求 表单形式
     *
     * @param url
     * @return
     */
    public static HttpResult doPost(String url) throws Exception {
        return doPost(url, null);
    }

    /**
     * 带参数的post请求 表单形式
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doPost(String url, Map<String, Object> map) throws Exception {
        // 1. 声明httppost
        HttpPost httpPost = new HttpPost(url);

        // 2.封装请求参数,请求数据是表单
        // 声明封装表单数据的容器
        List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
        if (map != null) {

            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封装请求参数到容器中
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        // 创建表单的Entity类
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");

        // 3. 把封装好的表单实体对象设置到HttpPost中
        httpPost.setEntity(entity);

        // 4. 使用Httpclient发起请求
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpPost);

        // 5. 解析返回数据,封装HttpResult
        // 5.1状态码
        int code = response.getStatusLine().getStatusCode();
        // 5.2 响应体内容
        String body = null;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        }

        HttpResult result = new HttpResult();
        result.setCode(code);
        result.setBody(body);
        return result;
    }

    /**
     * 1.带参数的post请求 body形式
     * 2.添加请求头header参数token
     * 3.设置超时时长
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doPostAndHeader(String url, Map<String, Object> map, String tokenK, String tokenV) throws Exception {
        // 1. 声明httppost
        HttpPost httpPost = new HttpPost(url);

        //2. 把body参数设置到HttpPost中
        httpPost.setEntity(new StringEntity(JSON.toJSONString(map)));
        /*
         * 添加请求头信息
         */
        // 浏览器表示
        httpPost.addHeader("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.6)");
        // 传输的类型
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
        //在请求头header中添加token参数
        httpPost.addHeader(tokenK, tokenV);

        // 3. 使用Httpclient发起请求
        CloseableHttpClient httpclient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(CONNECT_TIMEOUT)//设置连接超时时间,单位毫秒。
                .setConnectionRequestTimeout(CONNECT_REQUEST_TIMEOUT)//设置从connect Manager获取Connection 超时时间,单位毫秒。这个属性是新加的属性,因为目前版本是可以共享连接池的。
                .setSocketTimeout(SOCKET_TIMEOUT)//请求获取数据的超时时间,单位毫秒。 如果访问一个接口,多少时间内无法返回数据,就直接放弃此次调用。
                .build();
        httpPost.setConfig(requestConfig);
        CloseableHttpResponse response = httpclient.execute(httpPost);

        // 4. 解析返回数据,封装HttpResult
        // 4.1状态码
        int code = response.getStatusLine().getStatusCode();
        // 4.2 响应体内容
        String body = null;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        }

        HttpResult result = new HttpResult();
        result.setCode(code);
        result.setBody(body);
        return result;
    }

    /**
     * 不带参数的put请求 表单形式
     *
     * @param url
     * @return
     */
    public static HttpResult doPut(String url) throws Exception {
        return doPut(url, null);
    }

    /**
     * 带参数的put请求 表单形式
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doPut(String url, Map<String, Object> map) throws Exception {
        // 1. 声明httpput
        HttpPut httpPut = new HttpPut(url);

        // 2.封装请求参数,请求数据是表单
        if (map != null) {
            // 声明封装表单数据的容器
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封装请求参数到容器中
                parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }

            // 创建表单的Entity类
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(parameters, "UTF-8");

            // 3. 把封装好的表单实体对象设置到HttpPost中
            httpPut.setEntity(entity);
        }
        // 4. 使用Httpclient发起请求
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpPut);

        // 5. 解析返回数据,封装HttpResult
        // 5.1状态码
        int code = response.getStatusLine().getStatusCode();
        // 5.2 响应体内容
        String body = null;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        }

        HttpResult result = new HttpResult();
        result.setCode(code);
        result.setBody(body);
        return result;
    }

    /**
     * 不带参数的delete 表单形式
     *
     * @param uri
     * @return
     * @throws Exception
     */
    public static HttpResult doDelete(String uri) throws Exception {
        return doDelete(uri, null);
    }

    /**
     * 带参数的delete 表单形式
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    public static HttpResult doDelete(String url, Map<String, Object> map) throws Exception {
        // 1.创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder(url);

        // 2.设置请求参数
        if (map != null) {
            // 遍历请求参数
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                // 封装请求参数
                uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
            }
        }

        // 3.创建请求对象httpGet
        HttpDelete httpDelete = new HttpDelete(uriBuilder.build());

        // 4.使用httpClient发起请求
        CloseableHttpResponse response = HttpClients.createDefault().execute(httpDelete);

        // 5.解析返回结果,封装返回对象httpResult
        // 5.1获取状态码
        int code = response.getStatusLine().getStatusCode();

        // 5.2 获取响应体
        // 使用EntityUtils.toString方法必须保证entity不为空
        String body = null;
        if (response.getEntity() != null) {
            body = EntityUtils.toString(response.getEntity(), "UTF-8");
        }
        HttpResult result = new HttpResult();
        result.setCode(code);
        result.setBody(body);
        return result;
    }
}

4.测试


import com.wugenet.springboot.util.HttpClientUtil;
import com.wugenet.springboot.util.HttpResult;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;

public class HttpClientTest {

    /**
     * get请求 不带参数
     */
    @Test
    public void doGetNoParameter() throws Exception {
        String url = "http://127.0.0.1:8889/user/listUser";
        HttpResult result = HttpClientUtil.doGet(url);
        System.out.println("result:" + result);
    }

    /**
     * get请求 带参数
     */
    @Test
    public void doGet() throws Exception {
        String url = "http://127.0.0.1:8889/user/listUserById";
        Map<String, Object> map = new HashMap<>();
        map.put("id","3");
        HttpResult result = HttpClientUtil.doGet(url,map);
        System.out.println("result:" + result);
    }

    /**
     * get请求 在请求头header中添加token参数
     */
    @Test
    public void doGetHeader() throws Exception {
        String url = "http://127.0.0.1:8889/user/getHeader";
        HttpResult result = HttpClientUtil.doGet(url);
        System.out.println("result:" + result);
    }

    /**
     * post请求 不带参数
     */
    @Test
    public void doPOstNoParameter() throws Exception {
        String url = "http://127.0.0.1:8889/user/addUser";
        HttpResult result = HttpClientUtil.doPost(url);
        System.out.println("result:" + result);
    }

    /**
     * post请求 带参数
     */
    @Test
    public void doPost() throws Exception {
        String url = "http://127.0.0.1:8889/user/addUser";
        Map<String, Object> map = new HashMap<>();
        map.put("username","zhangyimeng");
        HttpResult result = HttpClientUtil.doPost(url,map);
        System.out.println("result:" + result);
    }

    /**
     * post请求 带参数:body形式  请求头带token 
     */
    @Test
    public void doPostByHttpClient() throws Exception {
        String url = "http://XXXX";
        Map<String, Object> map = new HashMap<>();
        map.put("username","zhangyimeng");
        String tokenK = "accessToken";
        String tokenV = "123456789";
        HttpResult result = HttpClientUtil.doPostAndHeader(url, map,tokenK,tokenV);
        System.out.println("result:" + result);
    }


}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
HttpClient是一个非常常用的HTTP客户端库,可以用于发送HTTP请求并接收响应。在封装HttpClient时,我们可以考虑以下几点: 1. 连接池管理:HttpClient可以通过连接池来管理HTTP连接,从而提高性能。我们可以设置最大连接数、每个路由的最大连接数等参数,以便更好地利用连接池。 2. 超时设置:在发送HTTP请求时,我们需要设置超时时间,以避免请求过程中出现阻塞或超时等问题。可以设置连接超时时间、读取超时时间等参数。 3. 异常处理:在发送HTTP请求时,可能会出现各种异常情况,例如网络异常、连接超时等。我们需要对这些异常进行处理,以便及时发现问题并进行处理。 4. 请求头设置:在发送HTTP请求时,我们需要设置请求头,以便服务器能够正确地处理请求。可以设置User-Agent、Content-Type等参数。 5. SSL支持:如果需要发送HTTPS请求,则需要支持SSL协议。可以通过配置SSLContext来实现SSL支持。 下面是一个简单的HttpClient封装示例: ```java public class HttpClientUtil { private static final int MAX_TOTAL = 200; private static final int MAX_PER_ROUTE = 50; private static final int CONNECT_TIMEOUT = 5000; private static final int SOCKET_TIMEOUT = 10000; private static CloseableHttpClient httpClient; static { PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setMaxTotal(MAX_TOTAL); cm.setDefaultMaxPerRoute(MAX_PER_ROUTE); RequestConfig requestConfig = RequestConfig.custom() .setConnectTimeout(CONNECT_TIMEOUT) .setSocketTimeout(SOCKET_TIMEOUT) .build(); httpClient = HttpClients.custom() .setConnectionManager(cm) .setDefaultRequestConfig(requestConfig) .build(); } public static String doGet(String url, Map<String, String> headers) throws IOException { HttpGet httpGet = new HttpGet(url); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } } try (CloseableHttpResponse response = httpClient.execute(httpGet)) { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toString(entity); } } return null; } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序务虚论

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值