Summarize the commonly used HTTP interface protocol parameter passing methods at the front and back ends

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 ULRclearly queryStringwritten What is used is application/x-www-form-urlencodedthe format, but the front-end passes application/jsonthe 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 QueryStringon 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:

  1. /user/1On the path, parameters 1are passed through the path. Some front-ends will make mistakes in this style of passing parameters.URLRestFul
  2. userName=adminThis is a simple QueryStringparameter transfer, which is the most common and generally cannot be mistaken.
  3. arrays=a,b,c,dThis is done by QueryStringpassing an array, which is actually using ,separation.
  4. ids=1&ids=2&ids=3&ids=4This is also a way to pass array parameters. It is generally used less often and is prone to errors.

Backend interface code

We use SpringMVCthe framework to write interfaces, which can receive the above parameters through @PathVariableand two annotations. There are three main methods:@RequestParam

  1. The first is to receive parameters one by one on the method;
  2. The second is to use Map<String,Object>reception to pass parameters;
  3. The third method is to encapsulate an UserDTOobject 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:

  1. Two data types can be String[]used when receiving array parameters ;List<Long>
  2. The type when using Map<String,Object> mapthe received parameter must be type, and addValueObject@RequestParam
  3. Do not add annotations when using Userobjects 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:

  1. If the parameters passed are not URLsafe, you need toURLEncode
  2. POST, PUT, DELETEmethods also support URLpassing parameters.
  3. The maximum parameter length supported by different browsers using this URLsplicing 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 Bodyparameters is mainly used by the front-end to submit data to the server, such as adding data , modifying data , uploading files , etc. BodyThere are three main data formats commonly used by passing parameters:

  1. application/x-www-form-urlencodedThat is, form submission uses splicing parameters bodyin the message ;key=value
  2. application/jsonConvert the data into JSONformat and put it Bodyin;
  3. multipart/form-dataUsed for file upload.

HTTP message format

  • application/x-www-form-urlencodedFormat 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/jsonFormat message:
GET /user4/1
Content-Type: application/json

{
    "id": 1,
    "userName": "admin",
    "arrays": [
        "a",
        "b",
        "c",
        "d"
    ],
    "ids": [
        1,
        2,
        3,
        4
    ]
}

Precautions:

  1. GETMethods can also Bodypass parameters. Many people think that the GET method cannot Bodypass parameters, but it can only be passed application/json. If you have used it elasticsearch, you should know that data is passed through GETmethods when searching for data JSON.

Backend interface code

The type parameters received in the framework are common to the parameters passed in , and SpringMvcannotations are required for reception .Bodyapplication/x-www-form-urlencodedURLQueryStringapplication/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:

  1. @RequestBodyAnnotations can be used directly DTOto receive, or they can be used Stringto receive and converted manually DTO. 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:

  1. multipart/form-dataMainly 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 Headerparameters is mainly used for some common user authentication information, such as commonly used Authentication: Bearer , Cookieetc.

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

  1. 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.because userNamethese custom
    request headers do not meet the standards. This can be solved by adding configuration.RFC 7230reject-illegal-header: off

application.ymlAdded:

server:
  port: 80
  tomcat:
    reject-illegal-header: off

Backend interface code

Obtaining Headerparameters can be obtained request.getHeader(header)sequentially or @CookieValuethrough@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:

  1. CookieIt is added automatically by the browser, no need to request.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, sseetc.HTTP

Guess you like

Origin blog.csdn.net/whzhaochao/article/details/132888444