Attempting to test rest service with multipart file

后端 未结 1 2034
陌清茗
陌清茗 2021-01-23 15:25

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. Fr
相关标签:
1条回答
  • 2021-01-23 15:52

    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();
    
    0 讨论(0)
提交回复
热议问题