HttpClient入门三

我们在爬取网页的时候,由于需要不断的访问目标服务器,因此给目标服务器带来了很多的压力。

因此,很多访问量大的服务器都会有保护措施,如果检测到我们的行为,可以会禁止我们的ip访问。

这个时候,我们就需要使用到代理ip来进行访问了。

在HttpCLient中,提供了一个org.apache.http.client.config.RequestConfig这个类,可以通过它的custom()方法,

来取得它的内部类RequestConfig.Builder类来设置请求信息。

实例:

package com.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class Test03 {

    public static void main(String[] args) {
        
        /**
         * 使用HttpClents的静态方法createDefault()创建一个可关闭的Http客户端
         * 这个client中有很多重载的execute方法,可以用来执行请求
         */
        CloseableHttpClient client= HttpClients.createDefault();
        
        /**
         * 创建一个对指定地址的get请求,
         * 这个请求在执行之后,将会在response中返回一个entity
         * 在org.apache.http.client.methods包中提供了
         * 很多http方法,比如get,post,head之类的
         */
        HttpGet get=new HttpGet("http://www.tuicool.com/");
        
        //定义一个HttpHost对象,里面有链接到目标服务器所需要的信息
        HttpHost proxy=new HttpHost("13.78.125.167",8080);
        
        //定义RequestConfig对象。里面含有一些请求的配置信息
        RequestConfig reqeustConfig=RequestConfig.custom().setProxy(proxy).build();
        
        //吧请求的配置设置到get请求中去
        get.setConfig(reqeustConfig);
        
        //设置请求头信息中的Agent,模拟浏览器
        get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0");
        
        CloseableHttpResponse response=null;
        try {
            /**
             * 使用默认的上下文执行请求
             * 返回request的response
             */
            response=client.execute(get);
            
            //打印出返回的状态栏
            System.out.println(response.getStatusLine());
            
            //从response中获取entity
            HttpEntity entity=response.getEntity();
            
            /**
             * 利用EntityUtils这个工具包中的toString这个静态方法
             * 可以轻松的获取entity中的内容,并且是以String类型返回
             */
            System.out.println(EntityUtils.toString(entity,"UTF-8"));
            
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

 

在实际的开发中,为了避免ip的限制,我们通常需要动态的更换ip来实现爬取。

 

posted @ 2017-07-26 13:19  Ouka傅  阅读(264)  评论(0编辑  收藏  举报