First release: Public account " Zhao Xiake "
Preface
I have been doing back-end development for many years. I have provided more than 1,000 interfaces to the front-end, if not 10,000. I have worked with 50 front-end developers, if not 100, and the front-end developers I have worked with range from fresh graduates to working professionals. As an experienced programmer with more than 10 years experience, I have encountered almost all kinds of people, from cute girls in the south of the Yangtze River to strong men in the northeast. I always encounter a problem in the process of connecting with the front-end. That is, our back-end interface has been provided. Self-test It also passed, but the front-end said that the interface was blocked. When we went to check, we found that most of the time it was not the interface that was blocked. In many cases, the posture used by the front-end was wrong. For example, the parameters clearly written in the interface were placed on the path, but the front-end passed them to the Internet, and the interface was ULR
clearly queryString
written What is used is application/x-www-form-urlencoded
the format, but the front-end passes application/json
the format. Therefore, this article summarizes the commonly used front-end and back-end parameter data formats to facilitate front-end and back-end developers to better understand the HTTP interface protocol parameter passing format.
1. Passing parameters through HTTP URL
This method is the simplest and most commonly used parameter passing method. It is usually used by the front end to obtain data from the back end. There are two types of parameter passing through URL. One is to put the parameters on the path, and the other is to put the parameters on the path URL
. The parameters are placed QueryString
on top, that is URL
, ?
behind
HTTP message format
GET /user/1?userName=admin&arrays=a,b,c,d&ids=1&ids=2&ids=3&ids=4
Precautions:
/user/1
On the path, parameters1
are passed through the path. Some front-ends will make mistakes in this style of passing parameters.URL
RestFul
userName=admin
This is a simpleQueryString
parameter transfer, which is the most common and generally cannot be mistaken.arrays=a,b,c,d
This is done byQueryString
passing an array, which is actually using,
separation.ids=1&ids=2&ids=3&ids=4
This is also a way to pass array parameters. It is generally used less often and is prone to errors.
Backend interface code
We use SpringMVC
the framework to write interfaces, which can receive the above parameters through @PathVariable
and two annotations. There are three main methods:@RequestParam
- The first is to receive parameters one by one on the method;
- The second is to use
Map<String,Object>
reception to pass parameters; - The third method is to encapsulate an
UserDTO
object to receive it.
@GetMapping("/user/{id}")
public UserDTO request(@PathVariable Long id, String userName, String[] arrays,@RequestParam List<Long> ids) {
return UserDTO.builder().id(id).build();
}
@GetMapping("/user2/{id}")
public Map<String,Object> user2(@PathVariable Long id,@RequestParam Map<String,Object> map) {
return map;
}
@GetMapping("/user3/{id}")
public UserDTO user3(@PathVariable Long id, UserDTO user) {
return user;
}
@Data
public class UserDTO {
private Long id;
private String userName;
private String[] arrays;
private List<Long> ids;
}
Precautions:
- Two data types can be
String[]
used when receiving array parameters ;List<Long>
- The type when using
Map<String,Object> map
the received parameter must be type, and addValue
Object
@RequestParam
- Do not add annotations when using
User
objects to receive parameters@RequestParam
Front-end calling interface code
URL上
For this parameter-passing method, the front-end can directly splice all the parameters together.
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost/user/1?userName=admin&arrays=a,b,c,d&ids=1&ids=2&ids=3&ids=4', true);
request.responseType = 'json';
request.onload = function () {
var data = this.response;
console.log(data);
};
request.send();
Precautions:
- If the parameters passed are not
URL
safe, you need toURLEncode
POST
,PUT
,DELETE
methods also supportURL
passing parameters.- The maximum parameter length supported by different browsers using this
URL
splicing is different. The following is the maximum parameter length supported by different browsers:
Browser | URL length limit |
---|---|
Internet Explorer | 2048 bytes |
360 speed browser | 65536 bytes |
Firefox(Browser) | 2118 bytes |
Safari(Browser) | 80000 bytes |
Opera(Browser) | 190000 bytes |
Google(chrome) | 8182 bytes |
2. Pass parameters through HTTP Body
Passing HTTP Body
parameters is mainly used by the front-end to submit data to the server, such as adding data , modifying data , uploading files , etc. Body
There are three main data formats commonly used by passing parameters:
application/x-www-form-urlencoded
That is, form submission uses splicing parametersbody
in the message ;key=value
application/json
Convert the data intoJSON
format and put itBody
in;multipart/form-data
Used for file upload.
HTTP message format
application/x-www-form-urlencoded
Format message:
POST /user3/1
Content-Type: application/x-www-form-urlencoded
userName=admin&arrays=a,b,c,d&ids=1&ids=2&ids=3&ids=4
application/json
Format message:
GET /user4/1
Content-Type: application/json
{
"id": 1,
"userName": "admin",
"arrays": [
"a",
"b",
"c",
"d"
],
"ids": [
1,
2,
3,
4
]
}
Precautions:
GET
Methods can alsoBody
pass parameters. Many people think that the GET method cannotBody
pass parameters, but it can only be passedapplication/json
. If you have used itelasticsearch
, you should know that data is passed throughGET
methods when searching for dataJSON
.
Backend interface code
The type parameters received in the framework are common to the parameters passed in , and SpringMvc
annotations are required for reception .Body
application/x-www-form-urlencoded
URL
QueryString
application/json
@RequestBody
@RequestMapping("/user3/{id}")
public UserDTO user3(@PathVariable Long id, UserDTO user) {
return user;
}
@RequestMapping("/user4/{id}")
public UserDTO user4(@PathVariable Long id,@RequestBody UserDTO user) {
return user;
}
@RequestMapping("/user5/{id}")
public UserDTO user4(@PathVariable Long id,@RequestBody String user) {
return JSONUtil.toBean(user,UserDTO.class);
}
Precautions:
@RequestBody
Annotations can be used directlyDTO
to receive, or they can be usedString
to receive and converted manuallyDTO
. This method is very useful when you don’t know what fields are in the data to be received, and you can print out the complete data sent by the other party.
Front-end calling interface code
function sendFormUrl() {
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/user3/1', true);
request.responseType = 'json';
request.onload = function () {
console.log(this.response);
};
var formData = new FormData();
formData.append('userName', "admin");
formData.append('arrays', "a,b,c,d");
formData.append('ids', "1");
formData.append('ids', "2");
formData.append('ids', "3");
formData.append('ids', "4");
request.send(formData);
}
function sendJson() {
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost/user4/1', true);
request.responseType = 'json';
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onload = function () {
console.log(this.response);
};
var body = {
"userName": "admin",
"arrays": [
"a",
"b",
"c",
"d"
],
"ids": [
1,
2,
3,
4
]
}
request.send(JSON.stringify(body));
}
Precautions:
multipart/form-data
Mainly used for file upload, you can parameterize another article of mine:
"One Demo handles the front-end and back-end large file uploading in pieces, resuming uploads, and seconds uploading"
Pass parameters through Header
Passing Header
parameters is mainly used for some common user authentication information, such as commonly used Authentication: Bearer
, Cookie
etc.
HTTP message format
GET /user7/1
Accept: application/json
userName : admin
Cookie: userName=admin;
arrays: a,b,c,d
ids:1
ids:2
ids:3
ids:4
Precautions
- When using SpringMVC, the request is rejected
java.lang.IllegalArgumentException: The HTTP header line [username : admin] does not conform to RFC 7230. The request has been rejected.
becauseuserName
these custom
request headers do not meet the standards. This can be solved by adding configuration.RFC 7230
reject-illegal-header: off
application.yml
Added:
server:
port: 80
tomcat:
reject-illegal-header: off
Backend interface code
Obtaining Header
parameters can be obtained request.getHeader(header)
sequentially or @CookieValue
through@RequestHeader
@RequestMapping("/user6/{id}")
public User user6(@PathVariable Long id, HttpServletRequest request) {
Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()){
String header= headerNames.nextElement();
log.info("{}->{}",header,request.getHeader(header));
}
return User.builder().id(id).build();
}
@RequestMapping("/user7/{id}")
public User user7(@PathVariable Long id, @CookieValue String userName, @RequestHeader String[] arrays, @RequestHeader List<Long> ids) {
return User.builder().id(id).userName(userName).arrays(arrays).ids(ids).build();
}
Front-end calling interface code
function sendHeader() {
var request = new XMLHttpRequest();
request.open('GET', 'http://localhost/user7/1', true);
request.responseType = 'json';
request.setRequestHeader("arrays","a,b,c,d");
request.setRequestHeader("ids","1");
request.setRequestHeader("ids","2");
request.setRequestHeader("ids","3");
request.setRequestHeader("ids","4");
request.onload = function () {
console.log(this.response);
};
request.send();
}
Precautions:
Cookie
It is added automatically by the browser, no need torequest.setRequestHeader("userName","admin")
add it
Summarize
This article summarizes the common methods of passing parameters through the HTTP interface protocol at the front and back ends, and demonstrates the message format, back-end acquisition method and front-end calling method of each parameter from the HTTP protocol, back-end JAVA code, and front-end JS code. Of course, there are also some More advanced parameter transmission methods, such as real-time push protocols based on websocket
, sse
etc.HTTP