org.springframework.web.client.HttpClientErrorException:400 null

2024-04-12

我写了测试FilterDataController。但我在执行测试时出现以下错误。当我手动发送 GET 请求时,我收到了正确的 JSON。

org.springframework.web.client.HttpClientErrorException: 400 null

    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:91)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:667)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:620)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:580)
    at org.springframework.web.client.RestTemplate.getForEntity(RestTemplate.java:312)
    at com.company.integration.tests.rest.StatisticEndpointTest.checkFilterDataControllerInvalidBodyResponse(StatisticEndpointTest.java:284)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)

My test:

@Test
public void checkFilterDataControllerInvalidBodyResponse() {
    String servicePath = getBaseUrl() + "/statistics/filters?startDate={startDate}&endDate={endDate}";
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(servicePath, String.class, "", "");
    assertThat(response, notNullValue());
    assertThat(response.getStatusCode(), equalTo(HttpStatus.BAD_REQUEST));
}

FilterDataController

/**
 * controller which provides possible filters data for UI
 */

@RestController
@RequestMapping("/statistics")
@Api(value = "/statistics",description = "API for possible filters data")
public class FilterDataController {

    public static final String DATE_FORMAT = "yyyy-MM-dd";

    @Autowired
    private FilterDataProvider filterDataProvider;

    @ApiOperation(value = "Get possible filter data",response = ResponseEntity.class)
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "The response data should be used as bricks in all future statistics requests"),
            @ApiResponse(code = 204, message = "Data not found. Select another timeframe")})
    @RequestMapping(path = "/filters", method = RequestMethod.GET)
    public ResponseEntity<Object> getPossibleFilterData(
            @RequestParam(value = "startDate") @DateTimeFormat(pattern=DATE_FORMAT) final Date startDate,
            @RequestParam(value = "endDate") @DateTimeFormat(pattern=DATE_FORMAT) final Date endDate) {
        if (startDate == null || endDate == null){
             throw new ValueNotAllowedException("Dates mustn't be null");
        }
        if (endDate.compareTo(startDate) == -1){
            throw new ValueNotAllowedException("End date should be after or equal start date");
        }
        else {
            Date newEndDate = endDate;
            if (startDate.equals(endDate)){
                newEndDate = new Date(endDate.getTime() + TimeUnit.DAYS.toMillis(1) - 1);
            }
            List<String> possibleMails =  Lists.newArrayList(filterDataProvider.getPossibleMails(startDate, newEndDate));

            <...>

            return new ResponseEntity<>(new FilterResponse(possibleMails, possibleSubjects, possibleCountries, possibleSizes, possibleStates),HttpStatus.OK);
        }
    }

    @ExceptionHandler(ValueNotAllowedException.class)
    void handleBadRequests(HttpServletResponse response, ValueNotAllowedException ex) throws IOException {
        response.sendError(HttpStatus.BAD_REQUEST.value(), ex.getMessage());
    }
}

来自的回应Postman:

GET

{
  "timestamp": 1476690591750,
  "status": 400,
  "error": "Bad Request",
  "exception": "com.services.exceptions.ValueNotAllowedException",
  "message": "Dates mustn't be null",
  "path": "/statistics/filters"
}

我发送到的参数getForEntity是正确的,因为当我发送相同的参数但日期正确时 - 它工作得很好。


你应该使用TestRestTemplate代替RestTemplate.

类 TestRestTemplate http://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/web/client/TestRestTemplate.html

RestTemplate 的便捷替代方案,适合集成测试。他们是容错,并且可以选择携带基本身份验证标头。如果 Apache Http Client 4.3.2 或更高版本可用(推荐),它将用作客户端,并且默认配置为忽略 cookie 和重定向。

Change

@Test
public void checkFilterDataControllerInvalidBodyResponse() {
    String servicePath = getBaseUrl() + "/statistics/filters?startDate={startDate}&endDate={endDate}";
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(servicePath, String.class, "", "");
    assertThat(response, notNullValue());
    assertThat(response.getStatusCode(), equalTo(HttpStatus.BAD_REQUEST));
}

To

@Test
public void checkFilterDataControllerInvalidBodyResponse() {
    String servicePath = getBaseUrl() + "/statistics/filters?startDate={startDate}&endDate={endDate}";
    TestRestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(servicePath, String.class, "", "");
    assertThat(response, notNullValue());
    assertThat(response.getStatusCode(), equalTo(HttpStatus.BAD_REQUEST));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

org.springframework.web.client.HttpClientErrorException:400 null 的相关文章

  • Thymeleaf 3 Spring 5 映射加载字符串而不是 HTML

    我正在尝试将 Spring 5 和 Thymeleaf 3 一起配置 我正在 Eclipse 上工作 我使用 全新安装 构建并使用 springboot run 运行应用程序 我已经设置了一个控制器和几个模板 但 Thymeleaf 似乎找
  • Jframe 内有 2 个 Jdialogs 的 setModal 问题

    当我设置第一个选项时 我遇到了问题JDialog模态 第二个非模态 这是我正在尝试实现的功能 单击 测试对话框 按钮 一个JDialog有名字自定义对话框 主要的将会打开 如果单击 是 选项自定义对话框主 其他JDialog named 自
  • 茉莉花单元测试 - 测试对象的未定义属性

    我有以下声明 expect A BAR name toEqual foo 由于我的对象 A 具有顶级属性 BAR 并且 bar 具有值 foo 传递 我想测试我的结构以确认属性 NONEXISTINGPROP 尚未定义 例如 expect
  • java inputstream 打印控制台内容

    sock new Socket www google com 80 out new BufferedOutputStream sock getOutputStream in new BufferedInputStream sock getI
  • Runtime.exec 处理包含多个空格的参数

    我怎样才能进行以下运行 public class ExecTest public static void main String args try Notice the multiple spaces in the argument Str
  • 提供节点名或服务名,或未知 Java

    最近我尝试运行我的 Java 项目 每当我运行它并将其打开到我得到的服务器地址时 Unable to determine host name java net UnknownHostException Caused by java net
  • Mockito 使用 @Mock 时将 Null 值注入到 Spring bean 中?

    由于我是 Spring Test MVC 的新手 我不明白这个问题 我从以下代码中获取了http markchensblog blogspot in search label Spring http markchensblog blogsp
  • 如何在单个查询中搜索 RealmObject 的 RealmList 字段

    假设我有一堂课 public class Company extends RealmObject private String companyId private RealmList
  • 如何在java中将日期格式从YYMMDD更改为YYYY-MM-DD? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我从机器可读代码中获取日期格式为 YYMMDD 如何将其更改为 YYYY MM DD 例如我收到 871223 YYMMDD 我想把它改成
  • 如何仅从 Firestore 获取最新更新的数据?

    在 Firestore 上发现任何更改时始终获取整个文档 如何只获取最近更新的数据 这是我的数据 我需要在第一次加载时在聊天中按对象顺序 例如 2018 09 17 30 40 msg和sendby 并且如果数据更新则仅获取新的msg和se
  • Jetty、websocket、java.lang.RuntimeException:无法加载平台配置器

    我尝试在 Endpoint 中获取 http 会话 我遵循了这个建议https stackoverflow com a 17994303 https stackoverflow com a 17994303 这就是我这样做的原因 publi
  • 如何在JPanel中设置背景图片

    你好 我使用 JPanel 作为我的框架的容器 然后我真的想在我的面板中使用背景图片 我真的需要帮助 这是我到目前为止的代码 这是更新 请检查这里是我的代码 import java awt import javax swing import
  • Java Swing - 如何禁用 JPanel?

    我有一些JComponents on a JPanel我想在按下 开始 按钮时禁用所有这些组件 目前 我通过以下方式显式禁用所有组件 component1 setEnabled false 但是有什么办法可以一次性禁用所有组件吗 我尝试禁用
  • 将 JavaFX FXML 对象分组在一起

    非常具有描述性和信息性的答案将从我这里获得价值 50 声望的赏金 我正在 JavaFX 中开发一个应用程序 对于视图 我使用 FXML
  • 手动设置Android Studio的JDK路径

    如何为 Android Studio 使用自定义 JDK 路径 我不想弄乱 PATH 因为我没有管理员权限 是否有某个配置设置文件允许我进行设置 如果您查看项目设置 您可以从那里访问 jdk 在标准 Windows 键盘映射上 您可以在项目
  • 在java中以原子方式获取多个锁

    我有以下代码 注意 为了可读性 我尽可能简化了代码 如果我忘记了任何关键部分 请告诉我 public class User private Relations relations public User relations new Rela
  • java 中的蓝牙 (J2SE)

    我是蓝牙新手 这就是我想做的事情 我想获取连接到我的电脑上的蓝牙的设备信息并将该信息写入文件中 我应该使用哪个 api 以及如何实现 我遇到了 bluecove 但经过几次搜索 我发现 bluecove 不能在 64 位电脑上运行 我现在应
  • Java 正则表达式中的逻辑 AND

    是否可以在 Java Regex 中实现逻辑 AND 如果答案是肯定的 那么如何实现呢 正则表达式中的逻辑 AND 由一系列堆叠的先行断言组成 例如 foo bar glarch 将匹配包含所有三个 foo bar 和 glarch 的任何
  • Log4j2 ThreadContext 映射不适用于parallelStream()

    我有以下示例代码 public class Test static System setProperty isThreadContextMapInheritable true private static final Logger LOGG
  • 如何更改 Spring OAuth2 上的response_type

    这是我使用 Instagram 进行 OAuth2 登录的配置 instagram client clientId clientId clientSecret clientSeret accessTokenUri https api ins

随机推荐

  • OAuth 2.0 访问令牌和刷新令牌

    我很难理解刷新和访问令牌的正确用法 我知道刷新令牌与授权相关 访问令牌与身份验证相关 我想更好地解释我的用例 以便有人可以在这里帮助我 我在 Google Merchant Center 中有一个多帐户中心 我想在我的代码中集成最新的 OA
  • 在新线程中调用支持 CUDA 的库

    我编写了一些代码并将其放入它自己的库中 该库使用 CUDA 在 GPU 上进行一些处理 我正在使用 Qt 构建 GUI 前端 作为加载 GUI 的一部分 我调用 CUresult res CUdevice dev CUcontext ctx
  • 全新的 React Native 应用程序在 run-ios xcode 8.3 上失败

    我刚刚使用他们的 CLI 界面创建了一个新的 React Native 应用程序 但在没有进行任何更改的情况下它失败了 当我尝试使用时我第一次注意到这一点version 0 45 1 它似乎仍然发生在version 0 46 1 我当前的版
  • 如何强制 rsync 创建目标文件夹

    Example rsync tmp fol1 fol2 fol3 foln user addr tmp fol1 fol2 fol3 foln 我的主要问题是远程计算机上不存在文件夹 tmp fol1 我可以使用哪些参数来强制 rsync
  • 在 Python 中将任何用户输入转换为 int

    我需要转换用户input to int 以下是我到目前为止所写的内容 但尚未成功 它只接受int 最终目标是让用户输入浮点数 例如 4 5 输出为 4 i input Enter any value print int i int接受整数字
  • 无法使用 matplotlib 设置脊柱线样式

    我尝试设置 matplotlib 图脊柱的线条样式 但由于某种原因 它不起作用 我可以将它们设置为不可见或使它们变细 但我无法更改线条样式 我的目标是将一个图分成两部分 以在顶部显示异常值 我想将相应的底部 顶部脊柱设置为点状 以便它们清楚
  • Django 中的动态逻辑查询生成器

    我在数据库中有 2 个表 class Param models Model s name models CharField max length 200 n name models CharField max length 200 clas
  • *nix 上的 rtfd/.webarchive

    所以我的任务是将 rtfd 文件转换为 tiff 首先要事 我们获取了文件夹中的附件 在 Mac 上为 rtfd 并对它们进行了成像 我的问题在于将 RTFD 拆分为多个 rtf 文件 一位同事建议通过我们访问权限有限的 Mac 将文件转换
  • 如何检查我的登录操作中是否存在用户?

    我开始使用新的身份管理并有一个简单的需求 当我的用户使用错误的名称登录时 它会报告密码错误 如何更改此设置 以便它还使用 dbcontext 方法检查用户名是否存在 public ActionResult Login LoginViewMo
  • vi 中可以每 4 个字符添加间距吗?

    vi 中是否可以每 4 个字符添加空格 如果是的话 有什么好的谷歌术语可以搜索来学习如何做类似的事情 要每 4 个字符添加一个空格 您可以使用以下命令 至少在 VIM 中 s 1 g 如果你谷歌 VIM Substitution 你应该会得
  • Visual Studio 2022 永远不会在解决方案和索引文件上显示项目

    有人知道如何解决这个问题吗 早期版本的 Visual Studio 会发生这种情况 例如 2019 和 2017 Visual Studio 不会永远在解决方案和索引文件上显示项目 连程序文件都无法运行 已经尝试了所有方法 完全卸载 Vis
  • 从其他组件访问激活的路线数据

    我们有组件 ka cockpit panel 它没有映射到任何路线 而是手动插入到其他组件中 如下所示 section class ka cockpit panel cockpit 1 pull left section
  • 如何从maven SNAPSHOT存储库下载SNAPSHOT版本?

    所以我有一个项目 我定期发布到 Maven 没有问题 我现在想要提供该项目的快照版本 所以我做了 mvn clean 部署 一切正常 如下所示 INFO 从 sonatype nexus snapshots 检索以前的内部版本号 上传中 h
  • 谷歌应用程序引擎。如何使用内存缓存或数据存储进行同步操作?

    我的主要目标是能够拥有一些同步方法 这些方法在完成之前不应被其他线程访问 如果我有普通的虚拟机 我会将此方法标记为同步 但在 GAE 中我有多个实例 我读到的所有关于此的帖子都说我应该使用内存缓存或数据存储 但具体如何呢 通常答案是重新设计
  • 为什么 GNU binutils 和 GDB 合并为一个包?

    https sourceware org git gitweb cgi p binutils gdb git https sourceware org git gitweb cgi p binutils gdb git 尤其是请参阅tags
  • Azure 数据工作室架构图?

    我最近刚刚下载了带有 SQL Server Express 的 Azure Data Studio 因为我使用的是 Linux 是否有实体关系图表功能 就像 SQL Server Management Studio 具有数据库图表功能一样
  • 无法接受 VSTS 邀请 - 选择的国家/地区为空

    我已邀请用户从我的 ADD 到 VSTS 他收到电子邮件并登录 在 我们需要更多详细信息 表格中 您需要输入姓名 电子邮件 We ll reach you at 和国家 地区 From 但是 那From 下拉列表为空 我无法选择任何国家 地
  • node.js google oauth2 示例停止工作 invalid_grant

    我正在编写一个使用谷歌日历API的程序 所以我使用了快速启动here https developers google com google apps calendar quickstart nodejs它起作用了 但最近相同的代码停止工作并
  • 如何将标签推送到 CI 中的分支?

    我想将手动作业添加到我的拉取请求中 以在运行手动作业时标记我的源分支 该标签将触发我的 bitrise 配置的构建 然而 当我尝试推送我的标签时 我遇到了这个问题 注意 我尝试将标签推送到的分支不受保护 git checkout CI CO
  • org.springframework.web.client.HttpClientErrorException:400 null

    我写了测试FilterDataController 但我在执行测试时出现以下错误 当我手动发送 GET 请求时 我收到了正确的 JSON org springframework web client HttpClientErrorExcep