使用HttpClient发送Http请求示例

1、概述

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新版本。

使用步骤一般如下:

  • 创建HttpClient对象
  • 创建请求方法的实例
  • 调用HttpClient对象的execute发送请求并获得响应对象HttpResponse
  • 释放连接

2、pom.xml

<dependencies>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>${httpclient.version}</version>
    </dependency>
    <dependency>
        <groupId>javax.ws.rs</groupId>
        <artifactId>javax.ws.rs-api</artifactId>
        <version>${javax.ws-version}</version>
    </dependency>

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>${fastjson.version}</version>
    </dependency>
</dependencies>

2、get请求

public String doGet(String url, Map<String, String> paramMap) {
    // 创建Http客户端
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建httpGet
    HttpGet httpGet = new HttpGet();
    // 响应对象
    CloseableHttpResponse response = null;

    String entityResult = "";
    try {
        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();
        httpGet.setConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(url);
        paramMap.forEach(uriBuilder::addParameter);
        URI uri = uriBuilder.build();
        httpGet.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        httpGet.setURI(uri);

        // 发送请求获得响应
        response = httpClient.execute(httpGet);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entityResult = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            //关闭响应
            if (null != response) {
                response.close();
            }
            //关闭客户端
            if (null != httpClient) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return entityResult;
}

3、post请求

public String doPost(String url, Map<String, String> basicParamMap, Object objectParam) {
    // 创建Http客户端
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建httpPost
    HttpPost httpPost = new HttpPost();
    // 响应对象
    CloseableHttpResponse response = null;

    String entityResult = "";
    try {
        // 配置信息
        RequestConfig requestConfig = RequestConfig.custom()
                // 设置连接超时时间(单位毫秒)
                .setConnectTimeout(5000)
                // 设置请求超时时间(单位毫秒)
                .setConnectionRequestTimeout(5000)
                // socket读写超时时间(单位毫秒)
                .setSocketTimeout(5000)
                // 设置是否允许重定向(默认为true)
                .setRedirectsEnabled(true).build();
        httpPost.setConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(url);

        // 普通参数:将参数放入键值对类NameValuePair中,再放入集合中
        List<NameValuePair> params = new ArrayList<>();
        basicParamMap.forEach((key, value) -> params.add(new BasicNameValuePair(key, value)));
        uriBuilder.setParameters(params);

        // 将对象转换为json字符串,并放入entity中
        StringEntity entity = new StringEntity(JSON.toJSONString(objectParam), StandardCharsets.UTF_8);
        httpPost.setEntity(entity);

        URI uri = uriBuilder.build();
        httpPost.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
        httpPost.setURI(uri);

        // 发送请求获得响应
        response = httpClient.execute(httpPost);

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            entityResult = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            //关闭响应
            if (null != response) {
                response.close();
            }
            //关闭客户端
            if (null != httpClient) {
                httpClient.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return entityResult;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值