In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
In this issue, the editor will bring you about how to parse the Post request parameters. The article is rich in content and analyzed and described from a professional point of view. I hope you can get something after reading this article.
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. This is the second article after "Get request parameter resolution posture summary of web part of 190824-SpringBoot series tutorials". For POST request mode, how to obtain request parameters?
The main content of this article includes the following postures
@ RequestBody json format
RequestEntity
MultipartFile file upload
i. Environment building
First of all, you have to build a web application before it is possible to continue the follow-up testing. Building a web application with SpringBoot is a relatively simple task.
Create a maven project with the following pom file
Org.springframework.boot spring-boot-starter-parent 2.1.7 UTF-8 UTF-8 Finchley.RELEASE 1.8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin spring-milestones Spring Milestones https://repo.spring.io/milestone false
Add project startup class Application.cass
@ SpringBootApplicationpublic class Application {public static void main (String [] args) {SpringApplication.run (Application.class);}}
In the parsing example that demonstrates the request parameters, we use the terminal's curl command to initiate the http request (mainly because the screenshot upload is too troublesome, or the terminal's text output is more convenient; the disadvantage is that it is not very intuitive)
Parsing of request parameters for II. POST
Next, let's officially move on to the enchanting pose section of parameter parsing, where we will introduce some common case (not all of which are used case).
All of the following methods are placed in the Controller ParamPostRest.
@ RestController@RequestMapping (path = "post") public class ParamPostRest {}
Before the formal introduction, it is highly recommended to take a look at the "Get request parameter parsing posture summary of the web part of the 190824-SpringBoot series of tutorials", because the posture of get parameters is also applicable in post parameter parsing, and the following content will not be described in detail again.
1. HttpServletRequest
First of all, let's take a look at the most basic way to use case. Just like case in get request, let's open an API first.
@ PostMapping (path = "req") public String requestParam (HttpServletRequest req) {return JSONObject.toJSONString (req.getParameterMap ());}
Let's test what happens under two kinds of post requests.
# regular form submission method # 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 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}'{}%
As you can see from the case above, when the data is submitted through the traditional expression, the acquisition of parameters is the same as that of get. However, of course, when the data is in json string format, the corresponding parameters cannot be obtained directly through javax.servlet.ServletRequest#getParameter.
Through debug, let's take a look at what we can do if we want to get the data when transmitting json string data.
The screenshot above shows that we get the post parameter from the requested InputStream; so when we actually use it, we need to note that the data in the stream can only be read once, and then it will be gone. This is very different from passing parameters using GET.
Note: if you have a section to print the request parameter log, you should pay attention to whether the data of the stream is read when getting the parameters passed by post, so that the correct data can not be obtained in the business!
2. RequestBody
When it comes to transmitting json string data, it is not convenient for the backend to obtain data directly through HttpServletRequest, so is there a more elegant posture? Let's take a look at the use of @ RequestBody annotations
Datapublic class BaseReqDO implements Serializable {private static final long serialVersionUID = 8706843673978981262L; private String name; private Integer age; private List uIds;} @ PostMapping (path = "body") public String bodyParam (@ RequestBody BaseReqDO req) {return req = = null? "null": req.toString ();}
You only need to add the @ RequestBody annotation to the parameter, and then the POST that supports the json string is submitted by this interface.
# 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 submitted ➜~ 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 parsed, but the form submission parameter method (application/x-www-form-urlencoded) is no longer supported.
3. RequestEntity
Using RequestEntity to parse parameters may not be very common, it is more appropriate to parse parameters submitted by json string, and it is relatively simple 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 cannot be submitted ➜~ 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 get the uploaded file, and 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.txthello, this is yhh's spring testworthy # use curl-F to upload files Pay attention to using the pose ➜~ 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 testworthy 5. Other
The above several request postures are different from those in the GET article. Please pay attention to the parsing of GET request parameters, which may also be applicable in POST requests. Why is it possible? Because in the post request, different content-type still has some influence on the parsing of parameters.
It should be noted that for traditional form submission (application/x-www-form-urlencoded), parameter parsing of post can still be used.
This is how to parse the Post request parameters shared by the editor. If you happen to have similar doubts, you might as well refer to the above analysis to understand. If you want to know more about it, you are welcome to follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.