【问题标题】:Spring/Postman Content type 'application/octet-stream' not supported不支持 Spring/Postman 内容类型“application/octet-stream”
【发布时间】:2018-10-27 22:22:39
【问题描述】:

我正在使用 Postman 发送以下请求:

我的控制器如下所示:

@RestController
@RequestMapping(path = RestPath.CHALLENGE)
public class ChallengeController {

    private final ChallengeService<Challenge> service;

    @Autowired
    public ChallengeController(ChallengeService service) {
        this.service = service;
    }

    @ApiOperation(value = "Creates a new challenge in the system")
    @RequestMapping(method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE},
        produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseStatus(HttpStatus.CREATED)
    public ChallengeDto create(@ApiParam(value = "The details of the challenge to create") @RequestPart("challengeCreate") @Valid @NotNull @NotBlank ChallengeCreateDto challengeCreate,
                           @ApiParam(value = "The challenge file") @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
        return service.create(challengeCreate, file);
    }
}

我已经尝试将“消耗”更改为将 APPLICATION_OCTET_STREAM_VALUE 删除为 MULTIPART_FORM_DATA_VALUE 并尝试将其删除,但这些都没有帮助。

如果您需要更多信息,请告诉我。 谢谢。

【问题讨论】:

  • 你可以尝试使用curl,有时邮递员会有奇怪的行为
  • @GustavoTopete 如何使用 curl 发送文件?
  • here

标签: spring rest postman


【解决方案1】:

使用@RequestParam 获取字符串和文件将解决这个问题。 在 Postman 中使用 Content-Type 作为“multipart/form-data”,在 Body 中将您的输入定义为 form-data。

参考https://stackoverflow.com/a/38336206/1606838

例子:

 @PostMapping(consumes = {"multipart/form-data"})
public Output send(@RequestParam String input, @RequestParam MultipartFile file) {

}

【讨论】:

    【解决方案2】:

    要让 Spring 的 @RequestPart 处理 json 对象,在 Postman 中 - 您需要将 json 对象作为 File 而不是 Text 发送。

    ChallengeCreateDto的内容放入一个json文件,保存为challenge.json。然后将该文件上传到 Postman 中,类型为 File。 我附上了 Postman 中的请求应该如何显示的屏幕截图,以使其更清晰。

    您还可以在较新版本的 Spring 中使用 @PostMapping 代替 @RequestMapping,如下所示

    @ResponseStatus(HttpStatus.CREATED)
    @PostMapping()
    public ChallengeDto create(@RequestPart("challengeCreate") ChallengeCreateDto challengeCreate, 
        @RequestPart("file") MultipartFile file) {
            return service.create(challengeCreate, file);
        }
    
    

    【讨论】:

    • 您也可以通过三点菜单显示“内容类型”列,并将内容类型设置为application/json。比先将 json 数据保存为文件更容易。
    • @DenisK 非常好的提示。
    【解决方案3】:

    Content-Type 是一个标头设置,默认情况下不选中它,默认为 application-octet-stream。只需选中标题功能区项下的框(一旦选中,默认为 application/json)。

    【讨论】:

      【解决方案4】:

      @Rokin 答案很好,但不需要将 json 放在文件中并上传。您也可以通过将内容类型传递给 json 对象来实现。 Postman 在发送表单数据时支持内容类型选项。进一步请参阅下面的自我描述图片。

      【讨论】:

      • 因为这是最受好评的答案,所以我添加了从@John 的答案中获得的这个额外要点 - Content-Type 是一个标头设置,默认为application-octet-stream。为避免该错误,请将标头中的Content-Type 值设置为包含application/json
      猜你喜欢
      • 2021-06-27
      • 1970-01-01
      • 2012-06-30
      • 1970-01-01
      • 2012-09-11
      • 2012-05-06
      • 2017-10-21
      • 2019-10-16
      • 1970-01-01
      相关资源
      最近更新 更多