As a perennial Http interface to provide a variety of backend, how to Get request parameters can be said to be a basic skill, this is “190824-SpringBoot series tutorial Web chapter Get request parameters parsing posture summary” after the second article, for POST request mode, and how to Get request parameters
The main content of this article includes the following positions
- @ RequestBody json format
- RequestEntity
- MultipartFile File upload
I. Environment construction
First of all, it is possible to build a Web application to continue the subsequent test. It is relatively simple to build a Web application with SpringBoot.
Create a Maven project with the following POM file
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.7</version>
<relativePath/> <! -- lookup parent from update -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</pluginManagement>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
Copy the code
Add the project startup class Application.cass
@SpringBootApplication
public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class); }}Copy the code
In the example of analyzing the request parameters, we use the terminal curl command to initiate the HTTP request. The downside is that it’s not very intuitive.)
II. POST Request parameter parsing
Next, we will enter the enchanting posture of parameter parsing. We will introduce some common cases (by no means include all use cases).
All of the following methods are in the ParamPostRest Controller
@RestController
@RequestMapping(path = "post")
public class ParamPostRest {}Copy the code
It is highly recommended to take a look at 190824-SpringBoot Tutorial Web: Get Request Pose parsing, because the Get pose is also applicable to POST parameter parsing, and will not be covered in detail below
1. HttpServletRequest
Let’s take a look at the basic use case, just like in the GET request, we’ll start with an interface
@PostMapping(path = "req")
public String requestParam(HttpServletRequest req) {
return JSONObject.toJSONString(req.getParameterMap());
}
Copy the code
What happens when we test the next two TYPES of POST requests
# Regular form submission
# content-type: application/x-www-form-urlencoded
➜ ~ curl 'http://127.0.0.1:8080/post/req' -X POST -d 'name=yihui&age=18'
{"name": ["yihui"]."age": ["18"]} %# json upload submit
➜ ~ curl 'http://127.0.0.1:8080/post/req' -X POST -H 'content-type:application/json; charset:UTF-8' -d '{"name": "yihui", "age": 20}'{} %Copy the code
As can be seen from the above case, when submitting data through the traditional expression, the method of obtaining parameters is the same as that of getting parameters. However, of course, is the incoming json string format data, directly through the javax.mail. Servlet. ServletRequest# getParameter get less than the corresponding parameters
If you want to retrieve json string data, what can you do
The screenshot above shows how we get the POST argument from the request’s InputStream; Therefore, it is necessary to pay attention to the actual use of the data in the stream can only be read once, after reading the data is gone; This is very different from using GET to pass parameters
Note: if you have a section that prints the request parameter log, you need to be careful when retrieving the parameter sent by POST. If you read the data from the stream, the correct data cannot be obtained in the service.
2. RequestBody
When it comes to passing json strings, it’s not convenient for the back end to get the data directly through HttpServletRequest. Is there a more elegant way to use it? Let’s look at the use of the @requestBody annotation
@Data
public class BaseReqDO implements Serializable {
private static final long serialVersionUID = 8706843673978981262L;
private String name;
private Integer age;
private List<Integer> uIds;
}
@PostMapping(path = "body")
public String bodyParam(@RequestBody BaseReqDO req) {
return req == null ? "null" : req.toString();
}
Copy the code
Just add the @requestBody annotation to the parameter, and the interface supports JSON string POST submissions
# json string data submission
➜ ~ curl 'http://127.0.0.1:8080/post/body' -X POST -H 'content-type:application/json; charset:UTF-8' -d '{"name": "yihui", "age": 20}'
BaseReqDO(name=yihui, age=20, uIds=null)%
Form data submission
➜ ~ curl 'http://127.0.0.1:8080/post/body' -X POST -d 'name=yihui&age=20'
{"timestamp": 1566987651551,"status": 415,"error":"Unsupported Media Type"."message":"Content type 'application/x-www-form-urlencoded; charset=UTF-8' not supported"."path":"/post/body"} %Copy the code
Instructions: Use@RequestBody
After annotations, the submitted JSON string can be parsed; Form submission parameters are no longer supported (application/x-www-form-urlencoded
)
3. RequestEntity
It may not be common to use RequestEntity to parse parameters, but it is also appropriate to parse parameters submitted by JSON strings, and the posture is simple
@PostMapping(path = "entity")
public String entityParam(RequestEntity requestEntity) {
return Objects.requireNonNull(requestEntity.getBody()).toString();
}
Copy the code
Use case as follows
# json string data submission
➜ ~ curl 'http://127.0.0.1:8080/post/entity' -X POST -H 'content-type:application/json; charset:UTF-8' -d '{"name": "yihui", "age": 20}'
{name=yihui, age=20}%
The form data submission will not work
➜ ~ curl 'http://127.0.0.1:8080/post/entity' -X POST -d 'name=yihui&age=19'
{"timestamp": 1566988137298,"status": 415,"error":"Unsupported Media Type"."message":"Content type 'application/x-www-form-urlencoded; charset=UTF-8' not supported"."path":"/post/entity"} %Copy the code
4. Upload MultipartFile
File upload is a more common, and more simple to support, there are two ways, one is to use a MultipartHttpServletRequest parameters for uploading files; One is with the @requestParam annotation
private String getMsg(MultipartFile file) {
String ans = null;
try {
ans = file.getName() + "=" + new String(file.getBytes(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
return e.getMessage();
}
System.out.println(ans);
return ans;
}
File uploads / * * * * * curl 'http://127.0.0.1:8080/post/file' - X POST - F 'file =@hello.txt'
*
* @param file
* @return* /
@PostMapping(path = "file")
public String fileParam(@RequestParam("file") MultipartFile file) {
return getMsg(file);
}
@PostMapping(path = "file2")
public String fileParam2(MultipartHttpServletRequest request) {
MultipartFile file = request.getFile("file");
return getMsg(file);
}
Copy the code
The test case is as follows
Create a text file➜ ~ vim hello. TXT hello, this is yhh's spring test! # curl -f: ➜ ~ curl 'http://127.0.0.1:8080/post/file' -F '[email protected]'
file = hello, this is yhh's spring test!
➜ ~ curl 'http://127.0.0.1:8080/post/file2' -F '[email protected]'
file = hello, this is yhh's spring test!
Copy the code
5. Other
In the POST request, it is possible to parse the parameters of a GET request. Because in post requests, different content-Types have an impact on parsing parameters;
Note that for traditional form submission (Application/X-www-form-urlencoded), parameter parsing of post can still be used
- @RequsetParam
- POJO (how beans are parsed)
- @pathvariable Parameter parsing
- Method parameter analysis
II. The other
0. Projects & Related posts
- 190824-SpringBoot Tutorial Web chapter summary of Get Request parameter parsing posture
- Project: github.com/liuyueyi/sp…
- Project: github.com/liuyueyi/sp…
1. An ashy Blog
As far as the letter is not as good, the above content is purely one’s opinion, due to the limited personal ability, it is inevitable that there are omissions and mistakes, if you find bugs or have better suggestions, welcome criticism and correction, don’t hesitate to appreciate
Below a gray personal blog, record all the study and work of the blog, welcome everyone to go to stroll
- A grey Blog Personal Blog blog.hhui.top
- A Grey Blog-Spring feature Blog Spring.hhui.top