简介
HTTP协定规定post提交的数据必须放在音讯主体中,然而协定并没有规定必须应用什么编码方式。服务端通过是依据申请头中的Content-Type字段来获知申请中的音讯主体是用何种形式进行编码,再对音讯主体进行解析。具体的编码方式包含:
application/x-www-form-urlencoded 最常见post提交数据的形式,以form表单模式提交数据。
application/json 以json串提交数据。
multipart/form-data 个别应用来上传文件。
一、 以form表单发送post申请
Reqeusts反对以form表单模式发送post申请,只须要将申请的参数结构成一个字典,而后传给requests.post()的data参数即可。
例:
# -*- coding: utf-8 -*- # author:Gary import requests url = 'http://httpbin.org/post' # 一个测试网站的url data = {'key1': 'value1', 'key2': 'value2'} # 你发送给这个的数据 r = requests.post(url, data=data) # 应用requests的post办法,data承受你想发送的数据 print(r.text) # 查看返回的内容
输入
外汇MT4教程https://www.kaifx.cn/mt4.html
{ “args”: {}, “data”: “”, “files”: {}, #你提交的表单数据 “form”: { “key1”: “value1”, “key2”: “value2” }, “headers”: { …… “Content-Type”: “application/x-www-form-urlencoded”, …… }, “json”: null, …… }
能够看到,申请头中的Content-Type字段已设置为application/x-www-form-urlencoded,且data = {‘key1’: ‘value1’, ‘key2’: ‘value2’}以form表单的模式提交到服务端,服务端返回的form字段即是提交的数据。
二、 以json模式发送post申请
能够将一json串传给requests.post()的data参数,
# -*- coding: utf-8 -*- # author:Gary import requests import json url = 'http://httpbin.org/post' # 一个测试网站的url json_data = json.dumps({'key1': 'value1', 'key2': 'value2'}) # 你发送给这个的数据,数据格式转为json r = requests.post(url, data=json_data) # 应用requests的post办法,data承受你想发送的数据 print(r.text) # 查看返回的内容
输入:
{ “args”: {}, “data”: “{\”key2\”: \”value2\”, \”key1\”: \”value1\”}”, “files”: {}, “form”: {}, “headers”: { …… “Content-Type”: “application/json”, …… }, “json”: { “key1”: “value1”, “key2”: “value2” }, …… }
能够看到,申请头的Content-Type设置为application/json,并将json_data这个json串提交到服务端中。
三、 以multipart模式发送post申请(上传文件)
Requests也反对以multipart模式发送post申请,只需将一文件传给requests.post()的files参数即可。
# -*- coding: utf-8 -*- # author:Gary import requests url = 'http://httpbin.org/post' files = {'file': open('report.txt', 'rb')} # 目录下得有report.txt文件能力上传,rb是指以二进制格局关上一个文件用于只读。 r = requests.post(url, files=files) # 通过files参数指定你想发送的文件的内容 print(r.text)
输入:
{ “args”: {}, “data”: “”, “files”: { “file”: “Hello world!” }, “form”: {}, “headers”: {…… “Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”, …… }, “json”: null, …… }
文本文件report.txt的内容只有一行:Hello world!,从申请的响应后果能够看到数据已上传到服务端中。