You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Rest Assured/Java中关闭GET请求的自动重定向?

解决Rest Assured中禁用GET请求自动重定向的问题

问题核心

你调用OAuth2授权端点时,需要获取302响应头里的code参数,但Rest Assured默认自动跟随重定向,导致请求被转发后触发504错误;你尝试的redirects().follow(false)未生效,同时参数传递方式也存在错误。

解决方案

1. 正确配置禁止重定向

在given()块中明确配置禁止跟随重定向,同时设置最大重定向次数为0,确保配置生效:

given()
    .log().all()
    .redirects().follow(false) // 禁用自动跟随重定向
    .redirects().max(0) // 强制设置最大重定向次数为0
    .headers(headers)
    // 改用queryParam传递URL查询参数,替代错误的pathParam用法
    .queryParam("client_id", config.getProperty("idClient"))
    .queryParam("code_challenge", config.getProperty("codeChallenge"))
    .queryParam("code_challenge_method", "S256")
    .queryParam("response_type", "code")
    .queryParam("scope", config.getProperty("scope"))
    .queryParam("redirect_uri", config.getProperty("redirectURI"))
    .queryParam("csrf", token)
    .queryParam("decision", "allow")
    .queryParam("state", config.getProperty("state"))
.when()
.get(oAuthUrl); // 基础URL无需拼接参数,由queryParam自动处理

2. 排查全局配置冲突

如果上述配置仍无效,检查是否存在全局Rest Assured配置覆盖了请求级别的设置:

// 若存在这类全局配置,需修改为false或在请求中明确覆盖
RestAssured.config = RestAssured.config().redirect(RedirectConfig.redirectConfig().followRedirects(true));

3. 验证并提取目标参数

请求执行后,可直接获取302响应及目标参数:

Response response = given()
    // 上述配置内容
.when()
.get(oAuthUrl);

int statusCode = response.getStatusCode(); // 应返回302
String authCode = response.getHeader("Location").split("code=")[1].split("&")[0]; // 提取Location中的code参数

关键注意事项

  • 不要将URL查询参数用pathParam传递,必须使用queryParam,Rest Assured会自动完成参数拼接,避免格式错误。
  • redirects().follow(false)必须放在given()块内,确保在请求执行前完成配置。

内容的提问来源于stack exchange,提问作者Nacho

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 15:43:26