Attempting to test rest service with multipart file

后端 未结 1 2035
陌清茗
陌清茗 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 parameters = new LinkedMultiValueMap();
    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>(parameters, headers),
        String.class
    ).getBody();
    

    0 讨论(0)
提交回复
热议问题