• 设置请求头信息User-Agent


    设置请求头信息User-Agent来模拟浏览器。

    先来看User-Agent:

    当我们向服务器发送请求时,浏览器会将一些头信息附加上,然后发给服务器。

    如上图所示头信息(请求头信息 Request Headers)

    我们的代码:

    package com.zhi.httpClient2;
    
    import org.apache.http.HttpEntity;
    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 Demo {
    
    	public static void main(String[] args) throws Exception {
    		CloseableHttpClient closeableHttpClient=HttpClients.createDefault(); //1、创建实例
    		HttpGet httpGet=new HttpGet("http://www.tuicool.com"); //2、创建请求
    		
    		httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36 SE 2.X MetaSr 1.0");
    		
    		CloseableHttpResponse closeableHttpResponse=closeableHttpClient.execute(httpGet); //3、执行
    		HttpEntity httpEntity=closeableHttpResponse.getEntity(); //4、获取实体
    		System.out.println(EntityUtils.toString(httpEntity, "utf-8")); //5、获取网页内容,并且指定编码
    		
    		closeableHttpResponse.close();
    		closeableHttpClient.close();
    	}
    
    }
    

      

    httpGet.setHeader(String key,String value);

    参数是键值对的形式

  • 相关阅读:
    Excel入门
    夹缝中求和
    移动撤销
    CSP2020-j2 T4 方格取数
    CSP2020-j2 T3表达式(expr)
    直播 获奖(live)
    优秀的拆分(power)
    P5661 公交换乘
    P1160 队列安排
    P1083 借教室
  • 原文地址:https://www.cnblogs.com/mengxinrenyu/p/7633405.html
Copyright © 2020-2023  润新知