Handling HTTP 302 Redirects with HttpClient in Java: Custom Request Config and Response Processing

This article explains how to detect HTTP 302 redirects when using HttpClient for API testing, extract the Location header, adjust request configurations to disable automatic redirects and ignore cookies, and provides Java code examples for processing the response and managing the client pool.

FunTester
FunTester
FunTester
Handling HTTP 302 Redirects with HttpClient in Java: Custom Request Config and Response Processing

When using HttpClient for API testing, a redirect (HTTP 302) to another domain caused failures; the article explains how to detect the 302 status, extract the Location header, and include the redirect URL in a JSON response.

The solution modifies the request method to check the status code, adds logic to store the redirect URL, and adjusts HttpClient connection‑pool and RequestConfig settings to disable automatic redirects and ignore cookies.

/**
 * 获取响应实体
 * <p>会自动设置cookie,但是需要各个项目再自行实现cookie管理</p>
 * <p>该方法只会处理文本信息,对于文件处理可以调用两个过期的方法解决</p>
 *
 * @param request 请求对象
 * @return 返回json类型的对象
 */
public static JSONObject getHttpResponse(HttpRequestBase request) {
    if (!isRightRequest(request)) return new JSONObject();
    beforeRequest(request);
    JSONObject res = new JSONObject();
    RequestInfo requestInfo = new RequestInfo(request);
    if (HEADER_KEY) output("===========request header===========", Arrays.asList(request.getAllHeaders()));
    long start = Time.getTimeStamp();
    try (CloseableHttpResponse response = ClientManage.httpsClient.execute(request)) {
        long end = Time.getTimeStamp();
        long elapsed_time = end - start;
        if (HEADER_KEY) output("===========response header===========", Arrays.asList(response.getAllHeaders()));
        int status = getStatus(response, res);
        JSONObject setCookies = afterResponse(response);
        String content = getContent(response);
        int data_size = content.length();
        res.putAll(getJsonResponse(content, setCookies));
        int code = iBase == null ? -2 : iBase.checkCode(res, requestInfo);
        MySqlTest.saveApiTestDate(requestInfo, data_size, elapsed_time, status, getMark(), code, LOCAL_IP, COMPUTER_USER_NAME);
    } catch (Exception e) {
        logger.warn("获取请求相应失败!", e);
        if (!SysInit.isBlack(requestInfo.getHost()))
            new AlertOver("接口请求失败", requestInfo.toString(), requestInfo.getUrl(), requestInfo).sendSystemMessage();
    } finally {
        HEADER_KEY = false;
        if (!SysInit.isBlack(requestInfo.getHost())) {
            if (requests.size() > 9) requests.removeFirst();
            boolean add = requests.add(request);
        }
    }
    return res;
}

/**
 * 获取响应状态,处理重定向的url
 *
 * @param response
 * @param res
 * @return
 */
public static int getStatus(CloseableHttpResponse response, JSONObject res) {
    int status = response.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) logger.warn("响应状态码错误:{}", status);
    if (status == HttpStatus.SC_MOVED_TEMPORARILY)
        res.put("location", response.getFirstHeader("Location").getValue());
    return status;
}

/**
 * 获取请求超时控制器
 * <p>
 * cookieSpec:即cookie策略。参数为cookiespecs的一些字段。作用:
 * 1、如果网站header中有set-cookie字段时,采用默认方式可能会被cookie reject,无法写入cookie。将此属性设置成CookieSpecs.STANDARD_STRICT可避免此情况。
 * 2、如果要想忽略cookie访问,则将此属性设置成CookieSpecs.IGNORE_COOKIES。
 * </p>
 * @return
 */
private static RequestConfig getRequestConfig() {
    return RequestConfig.custom()
        .setConnectionRequestTimeout(HttpClientConstant.CONNECT_REQUEST_TIMEOUT)
        .setConnectTimeout(HttpClientConstant.CONNECT_TIMEOUT)
        .setSocketTimeout(HttpClientConstant.SOCKET_TIMEOUT)
        .setCookieSpec(CookieSpecs.IGNORE_COOKIES)
        .setRedirectsEnabled(false)
        .build();
}

The RequestConfig method disables redirects and sets the cookie specification to IGNORE_COOKIES, which can be applied either when creating the HttpClient pool or when configuring an individual HttpRequestBase instance.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaHttpClientRedirectHTTP 302RequestConfig
FunTester
Written by

FunTester

10k followers, 1k articles | completely useless

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.