In my company, I usually use GET and POST, data format corresponding to application/ X-wwW-form-urlencoded and application/json, wait a moment, I said these two data formats are like, you can understand. Because have not studied deeply, have not very deep impression.

For example, a post request in application/ JSON format would be written like this:

getBankList: (data) => { return api.post(`/blank/feng/`, data).then( (res) => { if (res.status === 0) { return res.data; } else { throw openNotification(res.status, res.msg); } },(err) => { throw err; }); }Copy the code

How do I write a delete request in application/ JSON format? That’s not the right way to write it.

getBankList: (data) => { return api.delete(`/blank/feng/`, data).then( (res) => { if (res.status === 0) { return res.data; } else { throw openNotification(res.status, res.msg); } }, (err) => { throw err; }); }Copy the code

Write it like this:

deleteTicket: (data) => { return api.delete(`/blank/feng/`, { data: data }).then( (res) => { return res; },(error) => { throw error; }); },Copy the code

1. Data format

This data format is typically seen in the CONTent-type (Internet media Type) of HTTP requests, which represents the media Type information in the request and response. It is used to tell the server how to process the request data, and to tell the client (typically the browser) how to parse the response data, such as displaying images, parsing and presenting HTML, and so on.

Note that it only tells the back end what type of data to parse, but the back end doesn’t know what I’m passing to it. Of course, if you pass an incorrect type, you’ll get an error.

1.1 application/x – WWW – form – urlencoded

The data is encoded in key/value format and sent to the server (the form’s default format for submitting data).

This is usually used in POST, but I usually use it in GET.

  getTicketInfo: (params) => {    
    return api.get(`/blank/feng?cinemaId=${params}`).then(      
        (res) => {        
            return res;      
        },(error) => {        
            throw error;      
        }    
    );  
  }
Copy the code

Maybe we passed parameters

title=test&sub[]=1&sub[]=2&sub[]=3
Copy the code

When you ask for it, you will find that it becomes

title=test&sub%5B%5D=1&sub%5B%5D=2&sub%5B%5D=3
Copy the code

This is because we encode the request when we send it.

X-www-form-urlencoded rules are URL coding rules, rules are more, I listed a few more common rules:

1. The character “a” – “z”, “a” – “z”, “0” – “9”, “”,” – “, “*”, and “_” are not encoded (in Chinese), coding;

2. Convert the space to a plus sign (+).

3. Convert non-text content to “%xy”, where xy is a two-digit hexadecimal value;

4. Place an & between each name=value pair.

Online encoding and decoding: www.jsons.cn/urlencode/

1.2 application/json

The application/ JSON content-type is used as the response header. In fact, more and more people now use it as a request header to tell the server that the body of the message is a serialized JSON string.

Due to the popularity of the JSON specification, json. stringify is natively supported by all browsers except the earlier versions of IE, and server-side languages have functions to handle JSON, so you don’t have to run into trouble with JSON.

Front-end to back-end Json, back-end to front-end Json, tacit understanding.

When we send data, we usually write something like this:

addOperator: (data) => { return api.post(`/blcank/feng`, data).then( (res) => { if (res.status === 0) { return res.data; } else { throw openNotification(res.status, res.msg); } }, (err) => { throw err; }); } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- call request and the parameters of the -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- data = {" name ":" feng ", "old" : 23, "handsome ": Yes,}Copy the code

When the request is sent, the parameters are placed directly in the request entity without any processing:

Compared to Application/X-wwW-form-Urlencoded, json format supports much more complex structured data than key-value pairs, making it ideal for RESTful interfaces.

RESTFUL is a style of design and development for web applications

1.3 multipart/form – the data

Unlike Application/X-www-form-urlencoded and Application/JSON, this is a multi-part multimedia type.

We often use this format when we upload images.

First a boundary is generated to divide the different fields. In the request entity each parameter starts with ——boundary, then additional information and parameter name, then blank lines, and finally the parameter content. Multiple parameters will have multiple boundary blocks.

You can upload both key and value pairs and files. When the uploaded field is a file, content-type specifies the file Type of the table name. Content-disposition, which describes some information about the field.

Because of boundary isolation, multipart/form-data can upload both files and key-value pairs. It uses key-value pairs, so multiple files can be uploaded.

Boundary can be understood as a grid. Data is installed in a grid. There are many grids that can be loaded with different data.

1.4 text/XML

This is a cumbersome data format, a remote call specification that uses HTTP as the transport protocol and XML as the encoding.

It sends a request like this:

The POST HTTP / 1.1 the content-type: http://www.example.com Text/XML <? XML version="1.0"?> <methodName>examples. GetStateName </methodName> <params> <param> <value><i4>41</i4></value> </param> </params> </methodCall>Copy the code

In JavaScript, there are also libraries that support data interaction in this way, which can support this data format very well. However, the XML structure is still too bloated, and JSON is more flexible and convenient for general scenarios.

2. Request mode

HTTP follows the Request/Response model. The Web browser sends a request to the Web server, which processes the request and returns the appropriate response. All HTTP connections are constructed as a set of requests and replies.

2.1 the GET

This is a request that we often use. According to the HTTP specification, GET is used to GET information, to request a specified resource.

And it should be safe and idempotent. Safe means that the operation is used to get information, not to modify it. In other words, GET requests should generally have no side effects. Idempotent means that multiple requests to the same URL should return the same result.

Also, GET requests are cacheable, and when we use the GET request method, the request may be cached by the browser.

When the request is sent, the GET method adds data to the URL; The length of the URL is limited (the maximum URL length is 2048 characters), so the GET method cannot pass excessively long data. Also, the data sent by the GET method only allows ASCII characters.

I said ASCII characters you may not understand, in short, numbers, uppercase letters, lowercase letters, symbols, Spaces are all ASCII characters, Chinese is not. But why can we use GET request to send Chinese?

Because GET has its own encoding rules: if the data is English letters/digits, send it as is, if it is a space, convert it to +, if it is Chinese/other characters, directly encrypt the string using BASE64, and GET as follows:

%E4%BD%A0%E5%A5%BD
Copy the code

In % XX, XX is the HEXadecimal ASCII of the symbol.

2.2 POST

The difference between POST and GET is often asked in interview questions.

POST is used to submit data to a specified resource for processing a request (for example, to submit a form or upload a file). The data is contained in the request body. POST requests may result in the creation of new resources and/or the modification of existing resources.

It says GET is secure and idempotent, so I’m going to refute it from the other side, GET is secure because it says that the operation is used to GET information, not to modify information, but the parameters in GET are put in the URL, so it’s easy to expose information.

The security of POST is not only that the parameters are not in the URL, but that the sent request is not saved in the browser history. There is also CSRF, a kind of network hacking technology, using POST can greatly avoid being attacked.

Cross Site Request Forgery (CSRF), meaning cross-site Request Forgery. After the user has logged in to the target website, the CSRF attacker induces the user to visit an attack page. By taking advantage of the trust of the target website to the user, the CSRF attacker initiates a forged user operation request to the target website on the attack page as the user to achieve the attack purpose.

GET/POST:

GET

POST

purpose

Access to information

Submit data to CHU

bookmarks

Bookmark

Do not bookmark

The cache

Can be cached

Can’t cache

The encoding type

application/x-www-form-urlencoded

Application/x – WWW – form – urlencoded or multipart/form – the data. Use multiple encoding for binary data.

history

The parameters remain in the browser history.

Parameters are not saved in the browser history.

A limit on the length of data

Yes. When data is sent, the GET method adds data to the URL; The length of the URL is limited (maximum URL length is 2048 characters).

Unlimited.

Restrictions on data types

Only ASCII characters are allowed.

There is no limit. Binary data is also allowed.

security

GET is less secure than POST because the data being sent is part of the URL.

Never use GET! When sending passwords or other sensitive information.

POST is more secure than GET because parameters are not saved in the browser history or web server logs.

visibility

The data is visible to everyone in the URL.

The data does not appear in the URL.

Then, I would like to correct the point in GET that the URL length of the GET method is limited (maximum URL length is 2048 characters). The comparison in the novice also mentions the data length limit, which is not wrong in the literal sense, but must be understood correctly.

There is no limit on the size of the URL parameter data submitted by the GET method. There is no limit on the length of the URL in the HTTP protocol. This limit is limited by the specific browser and server.

So, GET itself has no data length limit, but is restricted by the browser and server.

2.3 the CONNECT

In THE HTTP protocol, the CONNECT method opens a two-way communication channel between the client and the requested resource. It can be used to create a tunnel.

This method is not used very often, but what is it used for? One of the important functions is to climb over walls.

CONNECT uses the server as a proxy, allowing the server to access other web pages on behalf of the user and then return data to the user.

2.4 the DELETE

The DELETE request method is used to DELETE the specified resource.

DELETE is a very simple method, no request body, no return body, will not cache, very simple to tell you THAT I do not need her, I want to DELETE her, you just tell me whether the deletion is successful on the line.

If the DELETE method executes successfully, there are several possible status codes:

  • Status code202 (Accepted) indicates that the requested operation may be successful, but has not yet started.
  • Status code204 (No Content) indicates that the operation was performed, but no further information is available.
  • Status code200 (OK) indicates that the operation has been performed and the response provides a description of the relevant state.

2.5 the HEAD

HEAD Specifies the headers of the resource requested, and the headers are the same as those returned by the GET method. One usage scenario for this request method is to obtain the size of a large file before deciding whether to download it, thus saving bandwidth resources.

In simple terms, HEAD is similar to GET and can be thought of as nimi GET. It’s used when we want to get information about the data like whether it exists or not without getting the data.

2.6 the OPTIONS

The OPTIONS command is used to obtain the communication OPTIONS supported by the destination resource. The OPTIONS method can be used by clients for specific urls or for entire sites (by setting the URL to “*”).

I don’t think you understand what it does. This method is interesting because it is used to get the methods supported by the current URL. If the request is successful, it will include a header named “Allow” in the HTTP header, and the value is the supported method, such as “GET, POST”.

It has one big use: precheck requests in CORS.

In CORS, you can use the OPTIONS method to initiate a precheck request to see if the actual request can be accepted by the server. The access-control-request-Method header field in the pre-check Request packet tells the server the HTTP Method used for the actual Request. The access-control-Request-headers header field informs the server of the custom header field carried in the actual Request. Based on the information obtained from the precheck request, the server determines whether to accept the actual subsequent request.

2.7 PUT

The PUT request method uses the load in the request to create or replace the target resource.

In simple terms, PUT is used to send a request to the server. If the URI does not exist, the server is asked to create a resource based on the request. If it does exist, the server accepts the request and changes the original version of the URI resource.

PUT is also used in common development. It is used to send data to the server, but there is an important difference between PUT and POST. PUT usually specifies the location of the resource, while POST does not.

2.8 PATCH

PATCH Is used to partially modify resources.

The target address requested by PATCH and PUT methods is directed to the resource.

The PUT method has been used to represent overall resource coverage, while the POST method does not provide support for the standard patch format. Unlike PUT, and like POST, PATCH is non-idempotent, which means that multiple successive requests of the same nature will have different effects.

Entities provided by PATCH need to be parsed and executed on the server according to the definition of programs or other protocols to modify data on the server.

2.9 TRACE

TRACE implements loop-back testing of messages along the path to the target resource and provides a useful debug mechanism

My understanding is a protocol debugging method.

3. Respond to the packet

The message, a very important thing, I didn’t pay much attention to the message. Until one time, the interface returned 307 to me. Postman tests on both the front and back ends were ok, but the request was unsuccessful. Finally, the reason was found from the packet.

Packets can bring us a lot of information, which is helpful for interface debugging. At least when we are at a loss, we can pay attention to the information provided by packets.

Forget the request. Let’s look at the response.

After the client sends a request to the server, the server normally returns an HTTP response message after receiving and processing the request from the client, which is called the response packet.

Composition of 3.1

The HTTP response consists of four parts: the status line, the message header, the blank line, and the response body.

3.2 response headers

The response header consists of key and value pairs, one pair per line, separated by colons (:). Response header fields allow the server to pass additional information that cannot be placed in the status line. These fields mainly describe the server’s information and further information about the request-URI.

And that’s the point of the message that I want to make, that gives us a lot of information.

To list some of the more common response headers:

Response headers

instructions

Allow

Which request methods (such as GET, POST, etc.) are supported by the server.

Content-Encoding

The Encode method of a document. The Content Type specified by the Content-Type header is obtained only after decoding. Using GZIP to compress documents can significantly reduce the download time of HTML documents. Java’s GZIPOutputStream is handy for gZIP compression, but only Netscape on Unix and IE 4 and 5 on Windows support it. Therefore, the Servlet should check whether the browser supports GZIP by looking at the Accept-Encoding header (i.e. Request.getheader (” accept-encoding “)) and return gZip compressed HTML pages for browsers that do. Return a normal page for other browsers.

Content-Length

Represents the length of the content. This data is only needed if the browser is using a persistent HTTP connection. If you want to take advantage of persistent connections, you can write the output document to a ByteArrayOutputStream, look at its size when you’re done, and put that value in the Content-Length header. Finally, the content is sent via bytearRayStream.writeto (Response.getOutputStream ().

Content-Type

Indicates what MIME type the following document belongs to. Servlets default to Text /plain, but usually need to explicitly specify Text/HTML. Since content-type is often set, HttpServletResponse provides a dedicated method called setContentType.

Date

The current GMT time. You can use setDateHeader to set this header to avoid the trouble of converting the time format.

Expires

At what point should a document be considered expired and no longer cached?

Last-Modified

The last time the document was changed. The client can provide a date through the if-Modified-since request header, and the request will be treated as a conditional GET. Only documents that have been Modified by the specified time will be returned, otherwise a 304 (Not Modified) status will be returned. Last-modified can also be set with the setDateHeader method.

Location

Represents where the customer should go to extract the document. Location is usually not set directly, but via the sendRedirect method of HttpServletResponse, which also sets the status code to 302.

Refresh

Indicates how long, in seconds, the browser should refresh the document. In addition to refreshing the current document, you can also use setHeader(“Refresh”, “5; URL=http://host/path”) to let the browser read the specified page. Note that this is usually done by setting < META http-equiv =”Refresh” CONTENT=”5; URL=http://host/path” > because automatic refresh or redirection is important to HTML writers who can’t use CGI or servlets. However, with servlets, it is more convenient to set the Refresh header directly.

Note that Refresh means “Refresh this page or visit the specified page after N seconds,” not “Refresh this page or visit the specified page every N seconds.” Thus, continuous refreshes require sending a Refresh header each time, and sending a 204 status code prevents the browser from continuing to Refresh, either using the Refresh header or < META http-equiv =”Refresh”… >.

Note that the Refresh header is not part of the formal HTTP 1.1 specification, but is an extension, but is supported by both Netscape and IE.

Server

Server name. Servlets typically do not set this value; instead, the Web server sets it itself.

Set-Cookie

Set the Cookie associated with the page. Servlets should not use Response. SetHeader (” set-cookie “,…) Instead, use the dedicated method addCookie provided by HttpServletResponse. See below for a discussion of Cookie setting.

WWW-Authenticate

What type of Authorization information should the customer provide in the Authorization header? This header is required in the response with the 401 (Unauthorized) status line. For example, response.setheader (” www-authenticate “, “BASIC realm= \ “executives \ “”). Note that servlets generally do not handle this, and instead let the Web server’s specialized mechanism control access to password-protected pages (for example,.htaccess).

4. To summarize

When I was learning HTTP, I read a book called HTTP Diagram. After reading it, I kept asking myself, did I use this knowledge? With the continuous deepening of work and the continuous running-in of the back end, I feel that HTTP seems to be a bridge for the communication between the front and back ends. Only with a deeper understanding of HTTP can I go up and down the bridge more easily.