【问题标题】:Getting 400 Bad Request in response when I enter Date input in Swagger当我在 Swagger 中输入日期输入时收到 400 Bad Request 作为响应
【发布时间】:2020-07-07 01:26:51
【问题描述】:

我的一个端点在 Java 代码中采用 2 个参数,data/format typeDate。在 swagger 中,API 将预期输入显示为:

string($date-time)

(查询)

当我在两个参数框中输入2020-07-07T01:08:10Z 时,我得到状态码400 Bad request 作为响应。我也试过2020-07-07T01:08:10.873Z

我是否给出了错误的日期格式?请帮忙。

编辑:

@GetMapping("/findAllEventsWithoutLogin")
    public Collection<GeneralEvent> getAllEvents(@RequestParam("start_date") Date startDate,
            @RequestParam("end_date") Date endDate) {

package com.events.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2

@Configuration
public class SwaggerConfig {

    @Bean
    public Docket productApi() {

        return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any()).build();
    }
}

编辑:

仅供参考:当我在正文中传递日期时,相同的日期格式可以正常工作,但当我将其作为查询参数传递时则不行。下面工作正常。

【问题讨论】:

  • 我猜 Swagger 是错误的 - 它下面的代码期望与 Swagger 文档不同的东西。您的代码输入看起来不错。您可以访问底层服务吗?

标签: java spring-boot swagger swagger-ui swagger-2.0


【解决方案1】:

,您没有使用错误的日期格式。

可能还有其他原因导致后端 Java 服务器无法访问您的请求。请发布您的最小 java 代码,如果可能的话,还请大摇大摆最小的 yml 定义。因此,我们可以检查您面临的问题。

在问了各种各样的乒乓球问题,澄清了我的疑问。

我发现您的后端代码存在一个问题,即您使用 start_date 和 end_date java.util.Date 作为查询参数。但是您请求的字符串会引发解析IllegalArgumentException 并导致400 Bad Request。因此,要解决此问题,您需要更改后端代码以添加格式为 @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME),这在现场 baeldung 中得到了完美的说明。修改代码如下:

@GetMapping("/findAllEventsWithoutLogin")
    public Collection<GeneralEvent> getAllEvents(@RequestParam("start_date")  @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME) Date startDate,
            @RequestParam("end_date")  @DateTimeFormat (iso = DateTimeFormat.ISO.DATE_TIME) Date endDate) {

请查看此link 以详细了解此问题。

如果您想查看熟代码,请访问我的github

【讨论】:

  • 截图和代码端点不同。 searchEventsByCategoryWithoutLogin 和 findAllEventsWithoutLogin。请在点击休息服务时检查您是否使用了正确的端点。
  • 如果 start_date 和 end_date 有任何问题,尤其是日期格式转换,那么这些值将被分配为 null,但不会以 400 Bad Request 响应。
  • 是的,不小心复制了错误的屏幕截图。但大摇大摆地击中正确的终点,
  • 您的 java 后端代码存在一个问题,那就是您将 start_date 作为 String 发送并作为 java.util.Date 接收。因此,要解决此问题,您可以检查我将相应更新的答案部分。
猜你喜欢
  • 2021-03-27
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-19
相关资源
最近更新 更多