httpClient4.5简单使用实例

maven引入

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.12</version>
</dependency>

Java代码

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.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 org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class Httpclient4Test {

    @Test
    public void getUrl(){
        CloseableHttpClient client = null;
        CloseableHttpResponse response = null;
        try {
            client = HttpClients.createDefault();
            HttpGet httpGet = null;
            //无参数请求
//            httpGet = new HttpGet("https://www.baidu.com");
            //带参数的get请求
            URIBuilder uriBuilder = new URIBuilder("https://www.baidu.com/s");
            uriBuilder.setParameter("wd", "好");
            httpGet = new HttpGet(uriBuilder.build());
//            httpGet.setURI(new URI("https://www.baidu.com"));

            //配置
            RequestConfig config = RequestConfig.custom().setConnectTimeout(2000)
                    .setConnectionRequestTimeout(2000)
                    .setSocketTimeout(2000)
                    .build();
            httpGet.setConfig(config);

            //http请求header设置
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36 Edg/88.0.705.68");

            //发起get请求
            response = client.execute(httpGet);
            if(response.getStatusLine().getStatusCode() != 200){
                return;
            }
            HttpEntity entity = response.getEntity();
            String html = EntityUtils.toString(entity, "utf8");
            System.out.println(html);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Test
    public void poolTest(){
        //创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //设置最大连接
        cm.setMaxTotal(100);
        //设置每个主机(域名)的最大连接数(并发量大时,避免某一个使用过大而其他过小)
        cm.setDefaultMaxPerRoute(10);

        //通过连接池管理器获取链接
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        HttpPost httpPost = new HttpPost("https://search.xx.com/all");

        //参数定义
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("keyword", "电影"));

        CloseableHttpResponse response = null;
        try {
            //创建提交的表单对象
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, Consts.UTF_8);

            httpPost.setEntity(formEntity);
            //发起请求
            response = httpClient.execute(httpPost);
            if(response.getStatusLine().getStatusCode() != 200){
                return;
            }
            HttpEntity entity = response.getEntity();
            String html = EntityUtils.toString(entity, Consts.UTF_8);
            System.out.println(html);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(response != null) response.close();
                if(httpClient != null) httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

军大_j

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

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

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

打赏作者

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

抵扣说明:

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

余额充值