python實現(xiàn)http post四種請求體詳解
在HTTP協(xié)議中,POST請求通常用于向服務器提交數(shù)據(jù)。雖然協(xié)議本身不強制規(guī)定數(shù)據(jù)的編碼方式,但實際開發(fā)中形成了四種常見的Content-Type格式:
- application/x-www-form-urlencoded(表單提交)
- multipart/form-data(文件上傳)
- application/json(JSON數(shù)據(jù))
- text/xml(XML數(shù)據(jù))
本文將結合Python代碼(同時涵蓋傳統(tǒng)urllib2和現(xiàn)代requests庫),詳細演示如何實現(xiàn)這四種請求體。
一、四種請求體格式簡介
根據(jù)參考資料中的描述:
- application/x-www-form-urlencoded:瀏覽器原生表單默認格式,數(shù)據(jù)被編碼為鍵值對(如
key1=value1&key2=value2)。 - multipart/form-data:用于文件上傳,數(shù)據(jù)被分為多個部分,每部分包含字段名和內(nèi)容,由邊界符(boundary)分隔。
- application/json:將數(shù)據(jù)結構序列化為JSON字符串,目前最流行的API數(shù)據(jù)交換格式。
- text/xml:基于XML的遠程調(diào)用規(guī)范(如XML-RPC),數(shù)據(jù)以XML格式包裹。
二、環(huán)境準備
我們將使用Python 3.x進行演示。如果使用現(xiàn)代開發(fā),推薦安裝第三方庫requests(更簡潔):
pip install requests
若使用傳統(tǒng)方法,需注意Python 3中urllib2已拆分為urllib.request和urllib.error。
三、代碼實現(xiàn)
1. application/x-www-form-urlencoded
特點:數(shù)據(jù)格式為field1=value1&field2=value2,需進行URL編碼。
# 方法一:使用內(nèi)置庫 urllib(Python 3)
import urllib.parse
import urllib.request
url = "http://httpbin.org/post"
data = {"package": "com.tencent.lian", "version_code": "66"}
# 將字典編碼為application/x-www-form-urlencoded格式
encoded_data = urllib.parse.urlencode(data).encode('utf-8')
req = urllib.request.Request(url, data=encoded_data, method='POST')
# 設置Content-Type頭(可選,urllib會根據(jù)data類型自動設置)
req.add_header('Content-Type', 'application/x-www-form-urlencoded')
with urllib.request.urlopen(req) as response:
print(response.read().decode('utf-8'))
# 方法二(推薦):使用 requests 庫
import requests
response = requests.post(url, data=data) # 使用data參數(shù)
print(response.json())2. multipart/form-data
特點:用于表單混合數(shù)據(jù)(含文件),每個字段由boundary分隔。
參考資料中使用的是poster模塊,但現(xiàn)代Python更推薦使用requests直接處理。
# 方法一:使用requests(推薦)
import requests
url = "http://httpbin.org/post"
# 普通字段
data = {"package": "com.tencent.lian", "version_code": "66"}
# 文件字段
files = {
'file': ('report.txt', open('report.txt', 'rb'), 'text/plain')
}
response = requests.post(url, data=data, files=files) # files參數(shù)自動處理multipart
print(response.json())
# 方法二:使用poster模塊(Python 2遺留方案,Python 3需適配)
# 注:poster模塊可能不支持Python 3,此處僅作參考
# from poster.encode import multipart_encode
# from poster.streaminghttp import register_openers
# register_openers()
# datagen, headers = multipart_encode(data)
# req = urllib2.Request(url, datagen, headers)3. application/json
特點:數(shù)據(jù)為JSON字符串,需設置Content-Type: application/json。
import json
import requests
url = "http://httpbin.org/post"
data = {"package": "com.tencent.lian", "version_code": "66"}
# 使用requests(自動設置Content-Type為application/json)
response = requests.post(url, json=data) # 使用json參數(shù)
print(response.json())
# 使用urllib(手動編碼)
json_data = json.dumps(data).encode('utf-8')
req = urllib.request.Request(url, data=json_data, method='POST')
req.add_header('Content-Type', 'application/json')
with urllib.request.urlopen(req) as resp:
print(resp.read().decode('utf-8'))4. text/xml
特點:數(shù)據(jù)為XML格式,需手動構建XML字符串并設置正確Content-Type。
import requests
url = "http://httpbin.org/post"
# 構建XML數(shù)據(jù)
xml_data = """<?xml version="1.0" encoding="utf-8"?>
<request>
<package>com.tencent.lian</package>
<version_code>66</version_code>
</request>"""
headers = {'Content-Type': 'application/xml'} # 或text/xml
response = requests.post(url, data=xml_data.encode('utf-8'), headers=headers)
print(response.text)四、總結與對比
| 編碼類型 | 適用場景 | Python實現(xiàn)關鍵點 |
|---|---|---|
| x-www-form-urlencoded | 簡單表單提交 | urllib.parse.urlencode 或 requests.post(data=dict) |
| multipart/form-data | 文件上傳/混合表單 | requests.post(files=dict) 自動處理 |
| application/json | API交互(最常用) | requests.post(json=dict) 或手動 json.dumps |
| text/xml | 舊系統(tǒng)/XML-RPC | 手動構建XML字符串,設置headers |
建議:在現(xiàn)代Python開發(fā)中,優(yōu)先使用requests庫,它簡化了不同POST格式的處理。若需兼容Python 2或舊項目,可參考參考資料中的urllib2實現(xiàn)。
注意:文中示例使用http://httpbin.org/post作為測試端點,這是一個開源的HTTP測試服務,會返回請求的詳細信息,便于調(diào)試。實際開發(fā)中請?zhí)鎿Q為目標API地址。
到此這篇關于python實現(xiàn)http post四種請求體詳解的文章就介紹到這了,更多相關python http post四種請求體內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
- Python請求庫發(fā)送HTTP POST請求的示例代碼
- Python調(diào)用http-post接口的實現(xiàn)方式
- Python使用HTTP POST上傳WAV文件的方法
- python利用urllib和urllib2訪問http的GET/POST詳解
- python通過get,post方式發(fā)送http請求和接收http響應的方法
- python使用urllib2提交http post請求的方法
- Python模仿POST提交HTTP數(shù)據(jù)及使用Cookie值的方法
- python client使用http post 到server端的代碼
- Python使用Socket(Https)Post登錄百度的實現(xiàn)代碼
相關文章
Python functools.lru_cache裝飾器性能提升利器深入探究
本文將詳細介紹functools.lru_cache裝飾器的原理、用法以及適當?shù)膱鼍?以幫助你更好地利用這一功能,它可以用來緩存函數(shù)的輸出,以避免重復計算,從而顯著提高程序的執(zhí)行速度2024-01-01
Python實現(xiàn)讀取txt文件中的數(shù)據(jù)并繪制出圖形操作示例
這篇文章主要介紹了Python實現(xiàn)讀取txt文件中的數(shù)據(jù)并繪制出圖形操作,涉及Python文件讀取、數(shù)值運算及基于pylab庫的圖形繪制相關操作技巧,需要的朋友可以參考下2019-02-02
python數(shù)據(jù)結構之二叉樹的統(tǒng)計與轉(zhuǎn)換實例
這篇文章主要介紹了python數(shù)據(jù)結構之二叉樹的統(tǒng)計與轉(zhuǎn)換實例,例如統(tǒng)計二叉樹的葉子、分支節(jié)點,以及二叉樹的左右兩樹互換等,需要的朋友可以參考下2014-04-04

