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

REST Assured Java接口自动化用Bearer Token遇400错误求助

REST Assured Bearer Token调用GET接口返回400的排查与解决
  • 排查请求头冲突
    你的代码同时使用了headers(headerMap1)和auth().oauth2(...),REST Assured的auth().oauth2()会自动生成Authorization: Bearer <token>请求头。如果headerMap1中已经包含Authorization字段,会导致请求头重复或格式冲突,触发400错误。
    解决方式二选一:

    // 方式1:移除headerMap1中的Authorization字段
    Map<String, String> headerMap1 = getHeaders();
    headerMap1.remove("Authorization");
    Response response = given().headers(headerMap1).auth().oauth2(StepDefition_glue.key).get("https://test.sit1.api.com.au/exp/customer/explore/business");
    
    // 方式2:手动在headerMap1中设置Bearer Token,不再调用auth().oauth2()
    Map<String, String> headerMap1 = getHeaders();
    headerMap1.put("Authorization", "Bearer " + StepDefition_glue.key);
    Response response = given().headers(headerMap1).get("https://test.sit1.api.com.au/exp/customer/explore/business");
    
  • 验证Token有效性与格式
    确认StepDefition_glue.key是不带Bearer前缀的纯Token字符串(auth().oauth2()会自动添加前缀)。同时用Postman等工具直接调用该接口,携带相同Token测试,排除Token过期、无效或格式错误的问题。

  • 检查是否缺少必填请求参数
    部分GET接口要求必填查询参数(如分页参数、筛选条件),未传递会返回400。对照接口文档,添加所需参数:

    Response response = given()
        .headers(headerMap1)
        .auth().oauth2(StepDefition_glue.key)
        .queryParam("page", 1) // 示例参数,根据实际需求调整
        .queryParam("size", 10)
        .get("https://test.sit1.api.com.au/exp/customer/explore/business");
    
  • 打印完整请求日志定位问题
    添加日志打印,查看实际发送的请求头、URL等细节,确认是否存在非法字段或编码问题:

    Response response = given()
        .log().all() // 打印完整请求信息
        .headers(headerMap1)
        .auth().oauth2(StepDefition_glue.key)
        .get("https://test.sit1.api.com.au/exp/customer/explore/business");
    response.then().log().all(); // 打印完整响应信息
    
  • 确认URL正确性
    检查请求URL的拼写、路径是否与接口文档一致,同时确认sit1测试环境是否正常可用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:05:19