There are many people who use Spring Boot's @RequestPart
to define an endpoint that receives both files and JSON data.
However, some of them encounter difficulties with how to test such endpoints, which is why I am writing this article.
β¨οΈ Parameters with @RequestPart
Typically, this type of endpoint is shown in the following code:
@RestController
@RequestMapping("/form-data")
public class FormDataController {
@RequestMapping(value = "/json-and-file", method = POST)
String jsonAndFile(@RequestPart User user,
@RequestPart MultipartFile file) {
return "ok";
}
}
I like to use modern Java, so I use records instead of Lombok or manually writing getters and setters. How about you?
public record User(String id, String name) {}
π€ HTTP status code 415
When using an HTTP Client such as Yaak, after submitting parameters via Multi-Part, I received a 415
status code. How frustrating.
At this point, open Spring Boot's console and you will see a warning that the content type "application/octet-stream" is not supported. The 415 status code means that the server does not support the media type of the current parameter.
Obviously, the user
field is a JSON string, not a binary. Without setting the content type manually, the default value is wrong. Therefore, we just need to set the correct content type for the user
field.
Don't worry, your backend code is correct.
π Solution: Set the Content-Type
of the text field to application/json
Yaak is a very clean tool and I love it!
But it CAN'T help when faced with this complex scenario because it DOESN'T support set the content-type for text field of a multipart request. I tried Paw, Bruno and they DIDN'T work either.
Therefore, I have to use a professional tool that supports setting the content-type for each part, such as Apidog or Postman. BTW, I only found these two GUI tools can do.
After setting the user
field's content-type
to application/json
, I successfully received the HTTP status code 200
responded by Spring Boot.
The problem is solved. π
If you need a modern and professional API tool, try Apidog, which is a new versatile tool. Of course, Postman is also a good classic choice.
Would anyone use curl in this situation?
Top comments (0)