HttpClient的用法

1.httpClient的常见的用法,看这篇博客,还挺详细的

https://blog.csdn.net/justry_deng/article/details/81042379

2.有些后台会对请求的发送方进行验证,比如要求必须用微信浏览器访问,HttpClient 模仿微信浏览器发送请求

 HttpPost post=new HttpPost(scheme+"/topfirst.php?g=Wap&m=Vote&a=ticket");
 post.setHeader("User-Agent","Mozilla/5.0 (Linux; U; Android 2.3.6; zh-cn; GT-S5660 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 MicroMessenger/4.5.255"
        );
 post.setHeader("Referer", "https://mp.weixin.qq.com");

3,httpClient 4.X版本发送请求对于重定向的处理:

HttpGet 遇到重定向会自动执行重定向的请求,返回码为200

HttpPost 遇到重定向,返回的状态码是302,对于重定向的处理如下

 CloseableHttpClient client =HttpClientBuilder.create().build();
        HttpPost post=new HttpPost("http://localhost:9999/test.do");
        CloseableHttpResponse execute = client.execute(post);
        if (execute.getStatusLine().getStatusCode()==302){
            Header location = execute.getFirstHeader("Location");
            String  newUrl=location.getValue();
            HttpPost newPost=new HttpPost(newUrl);
            CloseableHttpResponse response = client.execute(newPost);
            System.out.println("状态:"+response.getStatusLine());
            System.out.println("返回内容:"+EntityUtils.toString(response.getEntity()));

        }

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值