关于HttpClient设置请求头消息为什么需要设置User-Agent这个属性的原因

很简单,模拟浏览器请求,防止被被请求方拦截

比如代码中没有设置的时候:

public class Demo01 {
 
    public static void main(String[] args) throws Exception{
        CloseableHttpClient httpClient=HttpClients.createDefault(); // 创建httpClient实例
        HttpGet httpGet=new HttpGet("http://www.XXX.com/"); // 创建httpget实例
        CloseableHttpResponse response=httpClient.execute(httpGet); // 执行http get请求
        HttpEntity entity=response.getEntity(); // 获取返回实体
        System.out.println("网页内容:"+EntityUtils.toString(entity, "utf-8")); // 获取网页内容
        response.close(); // response关闭
        httpClient.close(); // httpClient关闭
    }
}

那么你收回的信息很可能就是:

网页内容:<!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>

当我们加上请求头信息之后的代码:

public class Demo01 {
 
    public static void main(String[] args) throws Exception{
        CloseableHttpClient httpClient=HttpClients.createDefault(); // 创建httpClient实例
        HttpGet httpGet=new HttpGet("http://www.tuicool.com/"); // 创建httpget实例
        httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0"); // 设置请求头消息User-Agent
        CloseableHttpResponse response=httpClient.execute(httpGet); // 执行http get请求
        HttpEntity entity=response.getEntity(); // 获取返回实体
        System.out.println("网页内容:"+EntityUtils.toString(entity, "utf-8")); // 获取网页内容
        response.close(); // response关闭
        httpClient.close(); // httpClient关闭
    }
}

收到的信息:

就是原网页信息。

文章中案例信息来自:https://blog.csdn.net/u013215018/article/details/55045392

原创文章 25 获赞 5 访问量 2万+

猜你喜欢

转载自blog.csdn.net/weixin_41450959/article/details/97630951