关于使用httpclient的心得与体会

1.下载相应的Jar包:

<!-- httpClient组件 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

        <!-- Jsoup组件 -->
        <dependency>
            <!-- jsoup HTML parser library @ http://jsoup.org/ -->
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.10.2</version>
        </dependency>

2.创建一个httpclient的实例:

	   // 创建一个httpclient实例
		   HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
CloseableHttpClient httpclient = httpClientBuilder.build();

3.调用get,post方法:
HttpGet httpGet = new HttpGet(String url);
HttpPost httpPost=new HttpPost(String url);
4.创建一个返回对象:

CloseableHttpResponse response = null;
5.使用这个返回的对象来接收执行的请求:

response = httpclient.execute(httpGet);

需要try-catch;

6.消费实体的内容:

HttpEntity entity = response.getEntity();
String html = EntityUtils.toString(entity, "utf-8");

7.输出即可得到我们想要的网页内容

8.使用代理:

HttpHost proxy = new HttpHost(String host, int port);

Builder globalConfig = RequestConfig.custom();
globalConfig.setConnectTimeout(10000);// 设置最长的连接时间
		globalConfig.setSocketTimeout(30000);// 设置读取时间
httpGet.setConfig(globalConfig.setProxy(proxy).build());
9.使用帐号和密码的代理ip:

 CredentialsProvider credsProvider = null;
 credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(AuthScope.ANY,
        new UsernamePasswordCredentials("username", "password"));


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值