尝试使用multipart文件测试休息服务

Bil*_*Lee 1 rest spring

我正在尝试测试我创建的休息服务.该服务是一个帖子.

  1. 我想创建一个文件来传递参数(包括一个多部分文件).
  2. 从那里我试图在此时调用该服务.

非常确定无效的服务.但是,当我打电话给休息服务.我有一个简单的表单,只传递几个值,包括jpg.

这是代码.

HttpMessageConverter bufferedIamageHttpMessageConverter =   new ByteArrayHttpMessageConverter();
restTemplate.postForObject("http://localhost:8080/sendScreeenAsPostCard",  uploadItem.getFileData(),  String.class));
Run Code Online (Sandbox Code Playgroud)

我的方法签名是:

ResultStatus sendScreenAsPostcard( @RequestParam MultipartFile image, @RequestParamString userId) 
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误.

Could not write request: no suitable HttpMessageConverter found for request type [org.springframework.web.multipart.commons.CommonsMultipartFile]

Sin*_*hot 7

您需要模拟文件上传,这需要特定的内容类型标题,正文参数等.这样的事情应该可以解决问题:

// Fill out the "form"...
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<String, Object>();
parameters.add("file", new FileSystemResource("file.jpg")); // load file into parameter
parameters.add("blah", blah); // some other form field

// Set the headers...
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "multipart/form-data"); // we are sending a form
headers.set("Accept", "text/plain"); // looks like you want a string back

// Fire!
String result = restTemplate.exchange(
    "http://localhost:8080/sendScreeenAsPostCard",
    HttpMethod.POST,
    new HttpEntity<MultiValueMap<String, Object>>(parameters, headers),
    String.class
).getBody();
Run Code Online (Sandbox Code Playgroud)