这两天开发,经常用到后端访问别的接口,所以看了一下 ,后端发送请求,这里总结一下
1 ----------以form形式发送post请求
#定义访问的登录网址
url = 'http://httpbin.org/post'
#配置需要的数据
d = {'key1': 'value1', 'key2': 'value2'}
@发送请求
r = requests.post(url, data=d)
#打印返回结果
print(r.text)
# 输出
{ 
“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,且d = {'key1': 'value1', 'key2': 'value2'}以form表单的形式提交到服务端,服务端返回的form字段即是提交的数据。
2 ------------------以json形式发送post请求
# 查看json解码后的信息
print r.json()
# 文本信息输出
{ 
“args”: {}, 
“data”: “{\”key2\”: \”value2\”, \”key1\”: \”value1\”}”, 
“files”: {}, 
“form”: {}, 
“headers”: { 
…… 
“Content-Type”: “application/json”, 
…… 
}, 
“json”: { 
“key1”: “value1”, 
“key2”: “value2” 
}, 
…… 
}
3 ------------以multipart形式发送post请求
url = 'http://httpbin.org/post'
files = {'file': open('report.txt', 'rb')}
r = requests.post(url, files=files)
print r.text
# 输出
{ 
“args”: {}, 
“data”: “”, 
“files”: { 
“file”: “Hello world!” 
}, 
“form”: {}, 
“headers”: {…… 
“Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”, 
…… 
}, 
“json”: null, 
…… 
}
原文链接:https://blog.csdn.net/junli_chen/article/details/53670887