Use the RestTemplate in SpringBoot to send complex multipart requests

The multipart/form-data request body is essentially A request body contains multiple parts, each with its own separate header and body.

It is generally used for file uploads and requests to submit multiple data formats at once.

Here we demonstrate that when submitting a file, we also submit a JSON, a form data to the server, and SpringBoot handles the request.

Send multipart/form-data requests using RestTemplate


import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class MainTest {
	public static void main(String[] args) throws IOException {
		RestTemplate restTemplate = new RestTemplate();

		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.MULTIPART_FORM_DATA); // Multi-part form body

		MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
		// ----------------- form part
		multipartBodyBuilder.part("name"."KevinBlandy");
		/** * Each form item has a separate header * an additional header */ is added to this form item
		multipartBodyBuilder.part("skill", Arrays.asList("Java"."Python"."Javascript")).header("myHeader"."myHeaderVal");
		
		// ----------------- file part
		// Reads files from disk
		multipartBodyBuilder.part("file".new FileSystemResource(Paths.get("D:\\17979625.jpg")), MediaType.IMAGE_JPEG);
		// Read the file from classpath
		multipartBodyBuilder.part("file".new ClassPathResource("app.log"), MediaType.TEXT_PLAIN);
		
		// ----------------- json part
		// json form entry
		multipartBodyBuilder.part("json"."{\"website\ : \"SpringBoot Chinese Community \"}", MediaType.APPLICATION_JSON);

		// Build the complete message bodyMultiValueMap<String, HttpEntity<? >> multipartBody = multipartBodyBuilder.build(); ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://localhost/test", multipartBody, String.class); System.out.println(responseEntity); }}Copy the code

Controlller handles requests

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/test")
public class TestController {

	private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class);
	
	@PostMapping
	public Object test (HttpServletRequest request,
						@RequestParam("name") String name,
						@RequestParam("skill") String[] skills,
						@RequestParam("file") MultipartFile[] multipartFiles,
						@RequestParam("json") String json) throws IOException, ServletException {
		
		// Get the encapsulated data
		LOGGER.debug("name={}", name);
		LOGGER.debug("skill=[{}]", String.join(",", skills));
		for (MultipartFile multipartFile : multipartFiles) {
			LOGGER.debug("file,fileName={},size={},contentType={}", multipartFile.getOriginalFilename(), multipartFile.getSize(), multipartFile.getContentType());
		}
		LOGGER.debug("json={}", json);
		
		// Get the header defined in the specified part
		Part part = request.getPart("skill");
		String headerVal = part.getHeader("myHeader");
		LOGGER.debug("myHeader={}", headerVal);
		return "ok"; }}Copy the code

Log output

o.s.web.servlet.DispatcherServlet        : POST "/test", parameters={masked}
s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to io.springboot.twitter.web.controller.TestController#test(HttpServletRequest, String, String[], MultipartFile[], String)
i.s.t.web.controller.TestController      : name=KevinBlandy
i.s.t.web.controller.TestController      : skill=[["Java"."Python"."Javascript"]]
i.s.t.web.controller.TestController      : file,fileName=17979625.jpg,size=11224,contentType=image/jpeg
i.s.t.web.controller.TestController      : file,fileName=app.log,size=77,contentType=text/plain
i.s.t.web.controller.TestController      : json={"website": "SpringBoot Chinese Community"}
i.s.t.web.controller.TestController      : myHeader=myHeaderVal
m.m.a.RequestResponseBodyMethodProcessor : Using 'text/plain', given [text/plain, application/json, application/*+json, */*] and supported [application/json, application/*+json, text/plain, */*, text/plain, */*, application/json, application/*+json]
m.m.a.RequestResponseBodyMethodProcessor : Writing ["ok"]
o.s.web.servlet.DispatcherServlet        : Completed 200 OK
Copy the code

Read all data submitted by the client accurately