Post Request Parameters Analytical Posture Summary in the SpringBook Series of Tutorials web Papers

As a backend that provides various Http interfaces all the year round, how to obtain request parameters can be said to be a basic skill.< Analytical Posture Summary of Get Request Parameters in the 190824-SpringBook Series of Tutorials web Papers > In the second part, how can we get the request parameters in POST request mode?

The main contents of this article include the following postures

  • @ RequestBody JSON format
  • RequestEntity
  • MultipartFile file upload

<!-- more -->

I. Environmental Construction

First, we need to build a web application in order to continue the follow-up testing. It is relatively simple to build a web application with SpringBook.

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>

Add Project Startup Class Application.cass

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class);
    }
}

In the parsing example of demonstrating request parameters, we use curl command of the terminal to initiate http request (the main reason is that the screenshot upload is too troublesome, or the text output of the terminal is more convenient; the disadvantage is not very intuitive)

II. POST request parameter parsing

Next, we will formally enter the parametric analysis of the enchanting posture section, which will introduce some common cases (not all use cases are included).

All of the following methods are in the ParamPostRest Controller

@RestController
@RequestMapping(path = "post")
public class ParamPostRest {
}

Before making a formal introduction, I strongly recommend that you take a look at it.< Analytical Posture Summary of Get Request Parameters in the 190824-SpringBook Series of Tutorials web Papers Because the gesture of get parameter is also applicable in post parameter analysis, the following will not be described in detail again.

1. HttpServletRequest

First, let's look at the most basic use case. Like the case in the get request, let's start with an interface.

@PostMapping(path = "req")
public String requestParam(HttpServletRequest req) {
    return JSONObject.toJSONString(req.getParameterMap());
}

Let's test what happens with two post requests

# Routine 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 submission
➜  ~ curl 'http://127.0.0.1:8080/post/req' -X POST -H 'content-type:application/json;charset:UTF-8' -d '{"name": "yihui", "age": 20}'
{}%

As you can see from the case above, when the data submitted by the traditional way of expression is used to get parameters, the same gesture is used to get parameters; however, of course, when the data in json string format is passed in, the corresponding parameters can not be obtained directly through javax. servlet. ServletRequest getParameter.

Through debug, let's see what we can do if we want to get data when we pass json string data.

The screenshot above demonstrates that we retrieve the post parameter from the requested InputStream; therefore, it is important to note that the data in the stream can only be read once, and it will disappear after reading; this is quite different from using GET parameters.

Note: If you have an aspect of the print request parameter log, you need to pay attention to getting the parameters of post transmission, whether read the data of the stream, resulting in the business can not get the correct data!!!

2. RequestBody

As mentioned above, it is not convenient for the back end to get data directly through HttpServletRequest when transferring json string data. So is it more elegant to use posture? 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();
}

Just add the @RequestBody annotation to the parameter, and then the interface supports POST submission of the json string.

# 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"}%

Note: After using the @RequestBody annotation, the submitted json string can be resolved; however, the form submission parameter method (application/x-www-form-urlencoded) is no longer supported.

3. RequestEntity

It may not be very common to use Request Entity to parse parameters. It is also suitable for parsing parameters submitted by json strings and easy to use posture.

@PostMapping(path = "entity")
public String entityParam(RequestEntity requestEntity) {
    return Objects.requireNonNull(requestEntity.getBody()).toString();
}

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}%

# Form data submission is not good
➜  ~ 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"}%

4. MultipartFile file upload

File upload is also common and easy to support. There are two ways: one is to use the MultipartHttpServletRequest parameter to obtain uploaded files; the other is to use 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 upload
 *
 * 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);
}

The test case is as follows

# Create a text file
➜  ~ vim hello.txt
hello, this is yhh's spring test!

# Use curl-F to upload files and pay attention to posture
➜  ~ curl 'http://127.0.0.1:8080/post/file' -F 'file=@hello.txt'
file = hello, this is yhh's spring test!

➜  ~ curl 'http://127.0.0.1:8080/post/file2' -F 'file=@hello.txt'
file = hello, this is yhh's spring test!

5. Other

Some of the requests mentioned above are different from those in GET. Please note that the parsing method of GET request parameters may also be applicable in POST requests. Why is it possible? Because in post requests, different content-type s still have parsing effects on parameters.

It should be noted that for the traditional form submission (application/x-www-form-urlencoded) method, post parameter parsing can still be used.

  • @RequsetParam
  • POJO (BEAN Analysis)
  • @ Analysis of PathVariable Parameters
  • Method parameter analysis

II. Others

0. Project - related blog posts

1. Grey Blog

Letters are not as good as letters. The above contents are purely family statements. Due to limited personal abilities, there are inevitably omissions and errors. If you find bug s or have better suggestions, you are welcome to criticize and correct them. Thank you very much.

Below is a grey personal blog, which records all the blogs about study and work. Welcome to visit it.

Tags: Programming Spring JSON curl Maven

Posted on Wed, 28 Aug 2019 04:57:00 -0700 by ChroniX88