Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
846 views
in Technique[技术] by (71.8m points)

java - Spring Boot multipart content type HTTP Request using RestTemplate

I am trying to emulate this request using RestTemplate in Spring Boot

curl -X POST 
'https://my.craftar.net/api/v0/image/?api_key=123456789abcdefghijk123456789abcdefghijk' 
-F "item=/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/" 
-F "file=@back_cover.png"

Here's my code:

MultiValueMap<String, Object> params= new LinkedMultiValueMap<>();
params.add("item", "/api/v0/item/4fe672886ec142f6ab6d72d54acf046f/");

final String filename=file.getOriginalFilename();
Resource contentsAsResource = new ByteArrayResource(file.getBytes()){
                      @Override
                      public String getFilename(){
                        return filename;
                      }
};

HttpHeaders imageHeaders = new HttpHeaders();
imageHeaders.setContentType(MediaType.IMAGE_PNG);
HttpEntity<Resource> imageEntity = new HttpEntity<Resource>(contentsAsResource, imageHeaders);
params.add("file", imageEntity);

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.ALL));
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String,Object>> requestEntity =new HttpEntity<>(params,headers);

try {
    ResponseEntity<String> responseEntity = restTemplate.exchange(url,HttpMethod.POST, requestEntity, String.class);
    return responseEntity.getBody();
  } catch (final HttpClientErrorException httpClientErrorException) {
      return httpClientErrorException.getResponseBodyAsString();
  } catch (Exception exception) {
      return exception.getMessage();
  }

The above request throws a HttpClientErrorException and this what the response body looks like

{"error": {"message": "Expected multipart/form-data; boundary=<..> content but got multipart/form-data;boundary=x6G0xWVxdZX4n8pYNU8ihGAnCg4Twj3DgMARYDs.", "code": "WRONG_CONTENT_TYPE"}}

I have also tried using FileSystemResource, but it throws the same exception. The problem probably lies in formatting the data in multipart content-type.

If it can help, this is the code template generated by Postman on a successful request using Okhttp.

OkHttpClient client = new OkHttpClient();

MediaType mediaType = MediaType.parse("multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW");

RequestBody body = RequestBody.create(mediaType, 
"------WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Disposition: form-data; name="item"

/api/v0/item/3d8dcdd1daa54bcfafd8d1c6a58249b5/
------WebKitFormBoundary7MA4YWxkTrZu0gW

Content-Disposition: form-data; name="file"; filename="times_logo.png"
Content-Type: image/png


------WebKitFormBoundary7MA4YWxkTrZu0gW--");

Request request = new Request.Builder()
.url("https://my.craftar.net/api/v0/image/?api_key=c6d4750c7368806fab27294fba8d0f93d48e1e11")
.post(body)
.addHeader("content-type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW")
.addHeader("cache-control", "no-cache")
.addHeader("Postman-Token", "cf09a989-338e-4d68-8968-b30a43384e5f")
.build();

Response response = client.newCall(request).execute();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

just add the Resource to params instead of creating a HttpEntity

params.add("file", contentsAsResource);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...