catalogue
1, application/x-www-form-urlencoded
We all know that POST is generally used to submit data to the server, and POST is used to submit data four There are four formats of content type, especially the format of data in the body when http sends a request. The four forms are:
-
application/x-www-form-urlencoded: URL encoded.
-
Multipart / form data: key value pair data.
-
application/json: Json type data.
-
text/xml: xml.
preface
HTTP request methods specified in HTTP/1.1 protocol include OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE and CONNECT. POST is usually used to submit data to the server, mainly for submitting forms and uploading files.
HTTP protocol is an application layer specification based on TCP/IP protocol. The specification divides the HTTP request into four parts: request line, request header, empty line and request body. Similar to this:
The protocol stipulates that the data submitted by POST must be placed in the message body, but the protocol does not specify what encoding method the data must use. In fact, developers can decide the format of the message body by themselves, as long as the last HTTP request meets the above format.
However, it is meaningful for the server to parse the data successfully. General server languages such as PHP and Python, as well as their framework, have built-in functions to automatically parse common data formats. The server usually knows how the message body in the request is encoded according to the content type field in the request header, and then parses the body. So when it comes to the POST data submission scheme, it includes content type And the encoding method of the message body, which are officially introduced below.
1, application/x-www-form-urlencoded
1. Introduction
This is the most common way to submit data through POST. If the browser's native < form > form is not set with the enctype attribute, it will eventually submit data in the application/x-www-form-urlencoded mode. The request is similar to the following (irrelevant request headers are omitted in this article):
First, the content type is specified as application/x-www-form-urlencoded; Secondly, the submitted data is encoded in the way of key1 = val1 & key2 = val2, and both key and val are URL transcoded. Most server languages have good support for this method.
Many times, we use this method when submitting data with Ajax. For example, the default values of Ajax and content type of JQuery are application/x-www-form-urlencoded;charset=utf-8.
2. Instance
Write Python code:
import requests url = "http://httpbin.org/post" data = { "name" : " coco" , "age " : "18"} headers = {"Content-type " : " application/x-www-form-urlencoded"} content = requests.post(url=url , data=data, ).text print(content)
requests determines which method to use according to the incoming key. The above method uses urlencode to encode the data. Here, the parameter is passed in to data =. The parameter format is Python dict dictionary.
The printout is as follows:
{ "args": {}, "data": "", "files": {}, "form": { "age": "18", "name": "coco" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "16", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "python-requests/2.24.0", "X-Amzn-Trace-Id": "Root=1-61ab2730-50a148997859a1ec6be91aa0" }, "json": null, "origin": "121.35.100.58", "url": "http://httpbin.org/post" }
2, Multipart / form data
1. Introduction
This encoding method is usually used to transfer large file data, such as pictures or files, from the client to the server. It is a common POST data submission method. When we upload a file using a form, we must make the enctype of the < form > form equal to multipart / form data. This format is used to upload the file. Take a direct look at a request example:
POST http://www.example.com HTTP/1.1 Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryrGKCBY7qhFd3TrwA ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="text" title ------WebKitFormBoundaryrGKCBY7qhFd3TrwA Content-Disposition: form-data; name="file"; filename="chrome.png" Content-Type: image/png PNG ... content of chrome.png ... ------WebKitFormBoundaryrGKCBY7qhFd3TrwA--
First, a boundary The string boundary indicates that the following is the form content, followed by the name of the first key value pair in the form, and then a newline followed by the value. Regenerate into a boundary String boundary, used to split different key values. If you are transferring a file, you should also include the file name and file type information. This method is generally used to upload files, and the major server languages also have good support for it.
The two POST data modes mentioned above are supported natively by the browser, and only these two modes are supported by the original < form > form in the standard at this stage (specified by the enctype attribute of the < form > element, the default is application/x-www-form-urlencoded. In fact, enctype also supports text/plain, but it is rarely used).
With more and more Web sites, especially WebApp, all use Ajax for data interaction, we can define new data submission methods.
2. Instance
Write Python code:
import requests from requests_toolbelt import MultipartEncoder m = MultipartEncoder( fields={'field0': 'value1', 'field1': 'value2', 'field2': ('filename', open('data.txt', 'rb'), 'text/plain')} ) content = requests.post('http://httpbin.org/post', data=m,headers={'Content-Type': m.content_type}).text print(content) print(m.content_type)
Similarly, it is also a data = transmission parameter. The difference is that the data is encoded in different ways.
The printout is as follows:
{ "args": {}, "data": "", "files": { "field2": "" }, "form": { "field0": "value1", "field1": "value2" }, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "358", "Content-Type": "multipart/form-data; boundary=dd748892469a4b1d9b66f4ef3c875314", "Host": "httpbin.org", "User-Agent": "python-requests/2.24.0", "X-Amzn-Trace-Id": "Root=1-61ab2927-40509795067605f976c44f9a" }, "json": null, "origin": "121.35.100.58", "url": "http://httpbin.org/post" } multipart/form-data; boundary=dd748892469a4b1d9b66f4ef3c875314
3, application/json
1. Introduction:
application/json as the response head, everyone must be familiar with it. It is super much used and very convenient. Set the content type in the header, tell the server that the data exists in the form of Json string, and then decode the data with Json's method. In fact, more and more people use it as a request header to tell the server that the message body is the serialized Json string. Because of Jason With the popularity of the specification, all major browsers except the low version IE natively support JSON.stringify, and the server language also has functions to deal with Json. There will be no trouble using Json.
The Json format supports much more complex structured data than key value pairs. The Ajax function in Google's AngularJS is to submit the Json string by default. For example, the following code:
The final request sent is:
This scheme can easily submit complex structured data, which is especially suitable for RESTful Interface for. Major capture tools, such as Chrome's own developer tool, Firebug and Fiddler, will display Jason in a tree structure Data, very friendly.
2. Instance
Write Python code:
import requests import json url="http://httpbin.org/post" p_data = { "name ": "coco", "hobby": "coding"} content = requests.post(url, json=json.dumps(p_data), headers={ ' Content-Type' : "application/json"}).text print(content)
Json = is used to pass in the parameter. The format of the parameter is Json string. Therefore, json.dumps() is used to convert Python dict to Json string (actually, it is the str type of python, but the receiver will decode the string by Json).
The printout is as follows:
{ "args": {}, "data": "\"{\\\"name\\\": \\\"coco\\\", \\\"hobby\\\": \\\"coding\\\"}\"", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "45", "Content-Type": "application/json", "Host": "httpbin.org", "User-Agent": "python-requests/2.24.0", "X-Amzn-Trace-Id": "Root=1-61ab2a62-57152a3a2edb5caa5f5a9351" }, "json": "{\"name\": \"coco\", \"hobby\": \"coding\"}", "origin": "121.35.100.58", "url": "http://httpbin.org/post" }
4, text/xml
1. Introduction
It is a remote call specification using HTTP as the transmission protocol and XML as the encoding method. A typical XML-RPC request is like this:
XML-RPC protocol is simple and functional, and can be implemented in various languages. It is also widely used, such as WordPress's XML-RPC Api, search engine ping Service and so on. In JavaScript, there are also ready-made libraries to support data interaction in this way, which can well support the existing XML-RPC services. However, I think the XML structure is still too bloated, and it is more flexible and convenient to use Json in general scenarios.
2. Instance
Write Python code:
import requests # from requests_toolbelt import MultipartEncoder p_data = """ <?xml version="1.0"?> <methodCall> <methodName>examples.getStateName</methodName> <params> <param> <value><i4>41</i4></value> </param> </params> </methodCall> """ content = requests.post(url='http://httpbin.org/post',data=p_data,headers={'Content-Type':'text/xml'}).text print(content)
data = is used to pass parameters. The parameter type is a string, which must be written according to the syntax of xml.
The printout is as follows:
{ "args": {}, "data": "\n<?xml version=\"1.0\"?>\n<methodCall>\n <methodName>examples.getStateName</methodName>\n <params>\n <param>\n <value><i4>41</i4></value>\n </param>\n </params>\n</methodCall>\n", "files": {}, "form": {}, "headers": { "Accept": "*/*", "Accept-Encoding": "gzip, deflate", "Content-Length": "200", "Content-Type": "text/xml", "Host": "httpbin.org", "User-Agent": "python-requests/2.24.0", "X-Amzn-Trace-Id": "Root=1-61ab2b3c-3e4f5e570e15c53f19ab13a7" }, "json": null, "origin": "121.35.100.58", "url": "http://httpbin.org/post" }
Finally, if you want to get the above code, you can get it according to the contact information below (including Baidu online disk link and Alibaba cloud disk link).
Thanks to everyone who reads my article carefully. It's always necessary to have reciprocity when watching the rise and attention of fans all the way. If you can use the following materials, you can take them directly:
In my QQ technical exchange group, I have sorted out some technical materials of my software testing career in recent 10 years, including e-books, resume modules, various work templates, interview scriptures, self-study projects, etc. If you encounter problems in study or work, there will also be great gods in the group to help solve them. Group No. 798478386 (note CSDN555)