您的位置:首页 > 理论基础 > 计算机网络

HttpClients 如何自动处理重定向

2017-05-24 00:54 429 查看
HttpClient只是模拟一次tcp请求,浏览器则会帮你处理重定向、缓存等事情。这也就是为什么用浏览器表单post提交后,不管服务端如何重定向,都能正常接收到服务端返回的数据。
       但是用HttpClient呢,你会发现,请求后,会返回302,因为POST方式提交HttpClient是不会帮你处理重定向的。
       方法一:(自己手动处理)
        HttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost= new HttpPost(http://ip:sport/xxx);
        CloseableHttpResponse response = httpclient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();

        System.out.println("statusCode=="+statusCode); //返回码
        Header header=response.getFirstHeader("Location");
        //重定向地址

        String location =  header.getValue();

        System.out.println(location);
        //然后再对新的location发起请求即可
        HttpGet httpGet = new HttpGet(location);

        CloseableHttpResponse response2 = httpclient.execute(httpGet);

        System.out.println("返回报文"+EntityUtils.toString(response2.getEntity(), "UT-F-8"));

       方法二:(已有工具类)
       HttpClientBuilder builder = HttpClients.custom()

            .disableAutomaticRetries() //关闭自动处理重定向

            .setRedirectStrategy(new LaxRedirectStrategy());//利用LaxRedirectStrategy处理POST重定向问题
       CloseableHttpClient client = builder.build();
        HttpPost httpPost= new HttpPost(http://ip:sport/xxx);
        CloseableHttpResponse response = client.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();

        System.out.println("statusCode=="+statusCode); //返回码
         System.out.println("返回报文"+EntityUtils.toString(response.getEntity(), "UT-F-8"));

4000
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: