问题描述
想在 POSTMAN 中测试一个 post 请求.
Wanted to test a post request in POSTMAN.
public enum TimeUnit {
HOURS("hours"),
MINUTE("mins");
private String value;
public static TimeUnit get(String text) {
return Arrays.stream(TimeUnit.values())
.filter(a -> Objects.equals(a.getValue(), text))
.findFirst()
.orElse(null);
}
}
public final class SchoolTimeTable {
private Double value;
private TimeUnit unit;
public SchoolTimeTable (double value, TimeUnit unit) {
this.value = value;
this.unit=unit;
}
}
public class SchoolDto {
private String name;
private String address;
private MultipartFile profileImage;
private MultipartFile[] galleryImages;
private SchoolTimeTable openCloseTime;
}
Spring MVC 控制器
@PostMapping(value = "/schoolInfo", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<Object> saveSchoolInfo( @Parameter(required = true, schema = @Schema(implementation = SchoolDto.class)) SchoolDto schoolDto) throws IOException, InterruptedException {
...
}
我想在发布请求中发送 SchoolDto(邮递员:body->raw->json)以获得所需的结果.但我无法创建支持 SchoolTimeTable (Object) 和 MultipartFile 类型的 json.我什至不知道是否可以使用 JSON.注意:使用带有键/值的 body->form-data 也可以实现相同的效果.
I want to send SchoolDto (POSTMAN: body->raw->json) in post request to get desired result. But I am not able to create the json which supports SchoolTimeTable (Object) and MultipartFile types. I don't even know whether it is possible with JSON or not.Note: Same could be achieved using body->form-data with key/value.
请帮忙.
推荐答案
我认为您不应该在 application/json
请求中上传文件,为此您应该使用 multipart/表单数据
请求.您的请求可能包含三部分 profileImage
、galleryImages
和 schoolInfo
.
I think you should not upload files within a application/json
request, to do so you should use a multipart/form-data
request. Your request may have three parts profileImage
, galleryImages
and schoolInfo
.
从SchoolDto
类
修改你的方法签名以支持多部分请求
Modify your method signature to support the multipart request
@PostMapping(value = "/schoolInfo", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<Object> saveSchoolInfo(@RequestPart(value = "profileImage") MultipartFile profileImage, @RequestPart(value = "galleryImages") MultipartFile[] galleryImages, @RequestPart(value = "schoolInfo") SchoolDto schoolInfo) throws IOException, InterruptedException {
...
}
此外,您可以使用 RestDocumentationExtension
实施 @SpringBootTest
单元测试,以检查您的代码是否有效并生成一个 curl 请求示例将帮助您了解如何向您的端点发出请求
In addtion you can implement a @SpringBootTest
unit test using RestDocumentationExtension
to check whether your code works and to produce a curl request sample that will help you to understand how to make a request to your endpoint
这篇关于json中的MultipartFile和嵌套对象来测试POSTMAN中的post请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!