Unable to test the REST API developed with Spring Boot
我正在尝试测试用Spring引导创建的其余API。方法的签名如下:
1 2 | @RequestMapping(consumes ="multipart/form-data", method = RequestMethod.POST) public Response<String> upload(@RequestBody CsvUploadModel form) { |
以下是模型对象的详细信息:
1 2 3 4 5 6 | private char separator; private char quoteCharacter; private String metricName; private String groupName; private MultipartFile file; //getters and setters |
我尝试使用1访问此服务。铬邮差和2。简单的HTTP POST表单。每次出现错误时:415:不支持的媒体类型。
编辑:以下是多部分bean的bean配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | /** * Allow file uploads * * @return */ @Bean public MultipartConfigElement multipartConfigElement() { MultiPartConfigFactory factory = new MultiPartConfigFactory(); factory.setMaxFileSize("500MB"); factory.setMaxRequestSize("500MB"); return factory.createMultipartConfig(); } /** * Get the multipart resolver * * @return */ @Bean public MultipartResolver multipartResolver() { return new CommonsMultipartResolver(); } |
我试图将@requestbody更改为@requestparam,但没有成功。以下是邮递员的请求预览。
1 2 3 4 5 6 7 8 9 10 11 12 13 | POST /dev/wizard/upload HTTP/1.1 Host: localhost:10022 Cache-Control: no-cache ----WebKitFormBoundaryE19zNvXGzXaLvS5C Content-Disposition: form-data; name="metricName" test ----WebKitFormBoundaryE19zNvXGzXaLvS5C Content-Disposition: form-data; name="separator" , ----WebKitFormBoundaryE19zNvXGzXaLvS5C |
我有什么明显的遗漏吗?
谢谢
1 | @RequestBody CsvUploadModel form |
这要求存在一个可以读取类型为
为了使您的方法正常工作,您应该删除
1 | upload(CsvUploadModel form, @RequestParameter(required=false) MultipartFile file) |
绑定表单数据不需要
1 | form.setFile(file); |
可能有第三方转换器支持读取
尝试改装
1 2 3 4 5 | <dependency> <groupId>com.squareup.retrofit</groupId> retrofit</artifactId> <version>1.6.1</version> </dependency> |
.
1 2 3 4 5 6 7 8 | import retrofit.http.Body; import retrofit.http.POST; public interface IRestController { @POST("/api-name") public Response api(@Body Request request); } |
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import static org.junit.Assert.assertNotNull; import org.junit.Test; import retrofit.RestAdapter; public class TestRestAPI { private static final String SERVER ="http://localhost:8080"; private IRestController service = new RestAdapter.Builder() .setEndpoint(SERVER).build() .create(IRestController.class); @Test public void basicTest(){ Response response = service.api(new Request()); assertNotNull(response); } } |