不支持Spring / Postman内容类型'application / octet-stream'

时间:2018-05-17 15:17:19

标签: spring rest postman

我正在使用Postman发送以下请求: enter image description here

我的控制器看起来像这样:

@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并尝试删除它,但这些都没有帮助。

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

4 个答案:

答案 0 :(得分:13)

@Rokin Answer很好,但是不需要将json放在文件中并上传。您也可以通过将内容类型传递给j​​son对象来实现。 发送表格数据时,邮递员支持内容类型选项。有关更多信息,请参见下面的自我描述图像。

enter image description here

答案 1 :(得分:4)

要让Spring的@RequestPart与json对象一起使用,在Postman中-您需要将json对象作为文件而不是文本发送。

ChallengeCreateDto 的内容放入json文件中,并将其另存为Challenge.json。然后将此文件上传到Postman中,其类型为文件。 我已经附上了一个截图,其中显示了Postman中的请求应该如何使其更加清晰。 Postman Request Screenshot][1]][1

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

@ApiOperation(value = "Creates a new challenge in the system")
@ResponseStatus(HttpStatus.CREATED)
@PostMapping()
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);
    }


  [1]: https://i.stack.imgur.com/rpG2H.png

答案 2 :(得分:0)

Content-Type是标头设置,默认情况下未选中它,默认为application-octet-stream。只需选中标头功能区项下的复选框即可(一旦选中,默认为application / json)。 enter image description here

答案 3 :(得分:-1)

使用@RequestParam获取字符串和文件将解决此问题。 在Postman中,将Content-Type用作“多部分/表单数据”,在Body中,将您的输入定义为表单数据。

引用https://stackoverflow.com/a/38336206/1606838

示例:

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

}