HttpClient入门二

通过上一节我们已经可以实现对一个网站源码的抓取。

但是,有一些网站,在爬取的时候会出现如下的错误:

HTTP/1.1 503 Service Unavailable
<!DOCTYPE html>
<html>
    <head>
          <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
    <body>
        <p>系统检测亲不是真人行为,因系统资源限制,我们只能拒绝你的请求。如果你有疑问,可以通过微博 http://weibo.com/tuicool2012/ 联系我们。</p>
    </body>
</html>

503错误表示服务器拒绝的意思。

这种网站通过检测到我们不是浏览器的访问,来拒绝我们的请求。这个时候为了能够实现抓取,我们就需要模拟浏览器来实现抓取行为。

就需要在头信息中加入一些东西来模拟浏览器 

我们可以观察浏览器的请求头信息:

其中比较重要的就是User-Agent这个项目了。在HttpGet中也提供了一个setHeader的方法来设置头信息。

例子

package com.httpclient;

import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
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 Test02 {

    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/");
        
        //设置请求头信息中的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();
            }
        }
    }
}
原文地址:https://www.cnblogs.com/zerotomax/p/7227390.html