HttpClient4.3.3 禁止自动重定向

HttpClient4.3中默认允许自动重定向,导致程序中不能跟踪跳转情况,其实只需要在RequestConfig中setRedirectsEnabled(false)即可(默认是true):

设置RequestConfig

private RequestConfig createConfig(int timeout, boolean redirectsEnabled){
    retun RequestConfig.custom()
        .setSocketTimeout(timeout)
        .setConnectTimeout(timeout)
        .setConnectionRequestTimeout(timeout)
        .setRedirectsEnabled(redirectsEnabled)
        .build();
}
public void test(String url){
  CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(createConfig(5000, false));
        CloseableHttpResponse response = client.execute(httpGet);
        try {  
            Header h = response.getFirstHeader("Location");  
            if(h!=null) { 
                System.out.println("重定向地址:"+h.getValue());  
            }
        }
        finally {  
            response.close();
        }  
    }  
    finally { 
       client.close();  
    }
}

另外如发生重定向,response的状态码为302,不是200。

完整工具类

package com.chengxumiao.utils;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.LaxRedirectStrategy;
import org.apache.http.util.EntityUtils;
import org.springframework.http.HttpMethod;

import java.io.IOException;

public class HttpProxy {

    /**
     * 请求配置
     *
     * @param timeout          超时时间设置
     * @param redirectsEnabled HttpClient4.3中默认允许自动重定向
     * @return
     */
    private static RequestConfig createConfig(int timeout, boolean redirectsEnabled) {
        return RequestConfig.custom()
                .setSocketTimeout(timeout)
                .setConnectTimeout(timeout)
                .setConnectionRequestTimeout(timeout)
                .setRedirectsEnabled(redirectsEnabled)
                .build();
    }

    /**
     * Http 请求(Json格式参数)
     *
     * @param requestUrl
     * @param requestJson
     * @param httpMethod
     * @return
     * @throws Exception
     */
    public static String httpRequest(String requestUrl, String requestJson, HttpMethod httpMethod) {
        CloseableHttpClient httpClient = null;
        try {
            httpClient = HttpClients.createDefault();
            HttpResponse response;

            if (null == httpMethod) {
                throw new RuntimeException("Http Method should be Get, Post, Put");
            }

            if (HttpMethod.GET == httpMethod) {
                HttpGet httpGet = new HttpGet(requestUrl);
                httpGet.setConfig(createConfig(5000, false));
                response = httpClient.execute(httpGet);
            } else {
                HttpEntityEnclosingRequestBase requestBase = null;

                switch (httpMethod) {
                    case POST:
                        requestBase = new HttpPost(requestUrl);
                        break;
                    case PUT:
                        requestBase = new HttpPut(requestUrl);
                        break;
                }

                if (null != requestJson && !requestJson.trim().equals("")) {
                    StringEntity requestEntity = new StringEntity(requestJson, ContentType.APPLICATION_JSON);
                    if (requestBase != null) {
                        requestBase.setEntity(requestEntity);
                    }

                }
                requestBase.setConfig(createConfig(5000, false));
                response = httpClient.execute(requestBase);
            }

            if (response.getStatusLine().getStatusCode() == 302) {
                Header h = response.getFirstHeader("Location");
                if (h != null) {
                    System.out.println("重定向地址:" + h.getValue());

                    return "location:"+h.getValue();
                }
            }

            HttpEntity httpEntity = response.getEntity();
            return EntityUtils.toString(httpEntity, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

相关文章

Java 纯HTTP请求 禁止302自动重定向

两张趣图帮助你理解状态码的含义


未经允许请勿转载:程序喵 » HttpClient4.3.3 禁止自动重定向

点  赞 (1) 打  赏
分享到: