【问题标题】:Spring Rest Controller API with HttpEntity getting null body when testing with Open API使用 Open API 进行测试时,带有 HttpEntity 的 Spring Rest Controller API 获取 null 正文
【发布时间】:2022-09-24 00:12:05
【问题描述】:

我正在使用 Spring Boot 2.6.7 并使用 Open API springdoc-openapi-ui 1.6.4。我有 2 项服务。从第一个服务我使用休息模板连接到第二个服务。 在第一个服务中,在休息控制器 api 中,我使用了HttpEntity 来获取请求对象。相同的内容传递给 rest 模板。原因在于 HttpEntity,我正在传递请求正文以及其他一些标头。

我的控制器方法如下。

@PostMapping(value = \"/submit\", produces = MediaType.APPLICATION_JSON_VALUE)
@Operation(summary = \"API for submit\", description = \"Submit data\")
@ApiResponses(value = { @ApiResponse(responseCode = \"200\", description = \"OK\"),
        @ApiResponse(responseCode = \"400\", description = \"Bad request\", content = @Content(schema = @Schema(implementation = Failure.class))),
        @ApiResponse(responseCode = \"500\", description = \"Error\", content = @Content(schema = @Schema(implementation = Failure.class))), })
public ResponseEntity<Success<SubmitOpr>> submit(HttpEntity<OperationReq> httpEntity) throws Exception {
    log.info(\"Request Entity is {}\", httpEntity);
    log.info(\"Request Body is {}\", httpEntity.getBody());
    SuccessResponse<SubmitOpr> response = null;
    try {
        response = oprService.submit(httpEntity);
    } catch (Exception e) {
        log.error(\"Failure: {}\", e.getMessage());
        throw e;
    }
    return ResponseEntity.ok().body(response);
}

我的应用程序可以正常工作。并且使用邮递员客户端也可以正常工作。 但是当我使用 swagger UI 进行测试时,并没有得到预期的结果。当我调试时,httpEntity.getBody() is null

如果我从HttpEntity&lt;OperationReq&gt; httpEntity 更改为OperationReq httpEntity,然后相应地更改后续服务层方法,则该api 可以大摇大摆地正常工作。 但我不想改变这一点。因为我想通过 HttpEntity 并且另一件事是有很多类似的 API,并且很难在任何地方进行更改。

有没有更好的解决方案?

  • 你能告诉我们发送的招摇请求吗?
  • 此外,只需查看 Swagger-UI 中的请求正文就可以了。

标签: spring-boot swagger openapi springdoc springdoc-openapi-ui


【解决方案1】:

对于 HttpEntity 控制器方法参数,我有同样的 Swagger 行为。在我的情况下,问题是 Swagger 将 httpEntity 作为查询参数而不是正文发送。 我添加了一个 @io.swagger.v3.oas.annotations.parameters.RequestBody 注释,它解决了这个问题:

@io.swagger.v3.oas.annotations.parameters.RequestBody(
    required = true,
    description = "Put here your feature configuration DTO in a JSON format",
    content = @Content(
        mediaType = MediaType.APPLICATION_JSON_VALUE,
        examples = @ExampleObject(value = "{}")
    )
)
HttpEntity<String> httpEntity
                                                                      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2021-02-02
    • 1970-01-01
    • 2023-03-25
    相关资源
    最近更新 更多