Attempting to test rest service with multipart fil

2019-03-02 11:03发布

I am attempting to test a rest service I created. The service is a post.

  1. I wanted to create a file to pass the parameters(including a multi-part file).
  2. From there I am trying to call the service at this point.

Pretty sure the service that doesn't work. But when I call rest Service. I have a simple form that just passes in a couple values including the jpg.

Here is the code.

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

My method signature is:

ResultStatus sendScreenAsPostcard( @RequestParam MultipartFile image, @RequestParamString userId) 

That is the error I am getting.

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

标签: spring rest
1条回答
你好瞎i
2楼-- · 2019-03-02 12:03

You need to simulate a file upload, which requires a particular content type header, body parameters, etc. Something like this should do the trick:

// 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();
查看更多
登录 后发表回答