壹個http請求包括三個部分,為別為請求行,請求報頭,消息主體,類似以下這樣:
請求行?
請求報頭?
消息主體
HTTP協議規定post提交的數據必須放在消息主體中,但是協議並沒有規定必須使用什麽編碼方式。服務端通過是根據請求頭中的Content-Type字段來獲知請求中的消息主體是用何種方式進行編碼,再對消息主體進行解析。具體的編碼方式包括:
application/x-www-form-urlencoded?
最常見post提交數據的方式,以form表單形式提交數據。
application/json?
以json串提交數據。
multipart/form-data?
壹般使用來上傳文件。
2.7.1 以form形式發送post請求
Reqeusts支持以form表單形式發送post請求,只需要將請求的參數構造成壹個字典,然後傳給requests.post()的data參數即可。
url = 'htt.org/post'd = {'key1': 'value1', 'key2': 'value2'}r = requests.post(url, data=d)
print r.text12341234
輸出:
{?
“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.7.2 以json形式發送post請求
可以將壹json串傳給requests.post()的data參數,
url = 'httin.org/post's = json.dumps({'key1': 'value1', 'key2': 'value2'})r = requests.post(url, data=s)
print r.text12341234
輸出:
{?
“args”: {},?
“data”: “{\”key2\”: \”value2\”, \”key1\”: \”value1\”}”,?
“files”: {},?
“form”: {},?
“headers”: {?
……?
“Content-Type”: “application/json”,?
……?
},?
“json”: {?
“key1”: “value1”,?
“key2”: “value2”?
},?
……?
}
可以看到,請求頭的Content-Type設置為application/json,並將s這個json串提交到服務端中。
2.7.3 以multipart形式發送post請求
Requests也支持以multipart形式發送post請求,只需將壹文件傳給requests.post()的files參數即可。
url = 'htt.org/post'files = {'file': open('report.txt', 'rb')}r = requests.post(url, files=files)
print r.text12341234
輸出:
{?
“args”: {},?
“data”: “”,?
“files”: {?
“file”: “Hello world!”?
},?
“form”: {},?
“headers”: {……?
“Content-Type”: “multipart/form-data; boundary=467e443f4c3d403c8559e2ebd009bf4a”,?
……?
},?
“json”: null,?
……?
}
文本文件report.txt的內容只有壹行:Hello world!,從請求的響應結果可以看到數據已上傳到服務端中。