Python使用POST方法發(fā)送HTTP請求的15個示例代碼
以下是使用requests庫調(diào)用HTTP接口進行POST請求的15個示例:
1.發(fā)送簡單的POST請求:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://example.com', data=payload)
print(response.text)
2.發(fā)送JSON格式的POST請求:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://example.com', json=json.dumps(payload))
print(response.text)
3.發(fā)送XML格式的POST請求:
import requests
payload = '<xml><key1>value1</key1><key2>value2</key2></xml>'
response = requests.post('http://example.com', data=payload, headers={'Content-Type': 'application/xml'})
print(response.text)
4.發(fā)送文件的POST請求:
import requests
files = {'file': open('file.txt', 'rb')}
response = requests.post('http://example.com', files=files)
print(response.text)
5.發(fā)送二進制數(shù)據(jù)的POST請求:
import requests
data = b'\x00\xff\x00\xff'
response = requests.post('http://example.com', data=data, headers={'Content-Type': 'application/octet-stream'})
print(response.text)
6.發(fā)送多個文件的POST請求:
import requests
files = [('file1', open('file1.txt', 'rb')), ('file2', open('file2.txt', 'rb'))]
response = requests.post('http://example.com', files=files)
print(response.text)
7.發(fā)送表單的POST請求:
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('http://example.com', data=payload, headers={'Content-Type': 'application/x-www-form-urlencoded'})
print(response.text)
8.發(fā)送JSON格式的POST請求并帶認證信息:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
auth = ('user', 'password')
response = requests.post('http://example.com', json=json.dumps(payload), auth=auth)
print(response.text)
9.發(fā)送JSON格式的POST請求并帶Headers:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
headers = {'Content-Type': 'application/json'}
response = requests.post('http://example.com', json=json.dumps(payload), headers=headers)
print(response.text)
10.發(fā)送JSON格式的POST請求并帶Cookies:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
cookies = {'name': 'value'}
response = requests.post('http://example.com', json=json.dumps(payload), cookies=cookies)
print(response.text)
11.發(fā)送JSON格式的POST請求并設(shè)置超時時間:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
timeout = 10
response = requests.post('http://example.com', json=json.dumps(payload), timeout=timeout)
print(response.text)
12.發(fā)送JSON格式的POST請求并設(shè)置代理:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
proxies = {'http': 'http://proxy.example.com:8080'}
response = requests.post('http://example.com', json=json.dumps(payload), proxies=proxies)
print(response.text)
13.發(fā)送JSON格式的POST請求并設(shè)置SSL認證:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://example.com', json=json.dumps(payload), verify=True)
print(response.text)
14.發(fā)送JSON格式的POST請求并禁用SSL認證:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://example.com', json=json.dumps(payload), verify=False)
print(response.text)
15.發(fā)送JSON格式的POST請求并設(shè)置SSL認證證書:
import requests
import json
payload = {'key1': 'value1', 'key2': 'value2'}
cert = ('client.crt', 'client.key')
response = requests.post('https://example.com', json=json.dumps(payload),cert=cert)
print(response.text)
知識擴展
python實現(xiàn)http post四種請求體
在HTTP協(xié)議中,POST請求通常用于向服務(wù)器提交數(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ù))
本文將結(jié)合Python代碼(同時涵蓋傳統(tǒng)urllib2和現(xiàn)代requests庫),詳細演示如何實現(xiàn)這四種請求體。
1.四種請求體格式簡介
根據(jù)參考資料中的描述:
- application/x-www-form-urlencoded:瀏覽器原生表單默認格式,數(shù)據(jù)被編碼為鍵值對(如
key1=value1&key2=value2)。 - multipart/form-data:用于文件上傳,數(shù)據(jù)被分為多個部分,每部分包含字段名和內(nèi)容,由邊界符(boundary)分隔。
- application/json:將數(shù)據(jù)結(jié)構(gòu)序列化為JSON字符串,目前最流行的API數(shù)據(jù)交換格式。
- text/xml:基于XML的遠程調(diào)用規(guī)范(如XML-RPC),數(shù)據(jù)以XML格式包裹。
2.環(huán)境準備
我們將使用Python 3.x進行演示。如果使用現(xiàn)代開發(fā),推薦安裝第三方庫requests(更簡潔):
pip install requests
若使用傳統(tǒng)方法,需注意Python 3中urllib2已拆分為urllib.request和urllib.error。
3.代碼實現(xiàn)
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')
# 設(shè)置Content-Type頭(可選,urllib會根據(jù)data類型自動設(shè)置)
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())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)application/json
特點:數(shù)據(jù)為JSON字符串,需設(shè)置Content-Type: application/json。
import json
import requests
url = "http://httpbin.org/post"
data = {"package": "com.tencent.lian", "version_code": "66"}
# 使用requests(自動設(shè)置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'))text/xml
特點:數(shù)據(jù)為XML格式,需手動構(gòu)建XML字符串并設(shè)置正確Content-Type。
import requests
url = "http://httpbin.org/post"
# 構(gòu)建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)總結(jié)與對比
| 編碼類型 | 適用場景 | Python實現(xiàn)關(guā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 | 手動構(gòu)建XML字符串,設(shè)置headers |
建議:在現(xiàn)代Python開發(fā)中,優(yōu)先使用requests庫,它簡化了不同POST格式的處理。若需兼容Python 2或舊項目,可參考參考資料中的urllib2實現(xiàn)。
注意:文中示例使用http://httpbin.org/post作為測試端點,這是一個開源的HTTP測試服務(wù),會返回請求的詳細信息,便于調(diào)試。實際開發(fā)中請?zhí)鎿Q為目標API地址。
到此這篇關(guān)于Python使用POST方法發(fā)送HTTP請求的15個示例代碼的文章就介紹到這了,更多相關(guān)Python發(fā)送HTTP請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
從零學(xué)python系列之新版本導(dǎo)入httplib模塊報ImportError解決方案
在使用新版python打開舊版本代碼的時候,可能會有些報錯或者不兼容的情況出現(xiàn),今天我們就來分析其中的一種情況2014-05-05
Python實現(xiàn)的FTP通信客戶端與服務(wù)器端功能示例
這篇文章主要介紹了Python實現(xiàn)的FTP通信客戶端與服務(wù)器端功能,涉及Python基于socket的端口監(jiān)聽、文件傳輸?shù)认嚓P(guān)操作技巧,需要的朋友可以參考下2018-03-03
python實現(xiàn)合并多個list及合并多個django QuerySet的方法示例
這篇文章主要介紹了python實現(xiàn)合并多個list及合并多個django QuerySet的方法,結(jié)合實例形式分析了Python使用chain合并多個list以及合并Django中多個QuerySet的相關(guān)操作技巧,需要的朋友可以參考下2019-06-06
Python利用海龜畫圖turtle庫做一個籃球比賽計時畫面示例代碼
這篇文章主要介紹了Python利用海龜畫圖turtle庫做一個籃球比賽計時畫面的相關(guān)資料,文中通過代碼介紹的非常詳細,代碼實現(xiàn)了一個基本的計時器功能,需要的朋友可以參考下2024-12-12
Python實現(xiàn)將MySQL中所有表的數(shù)據(jù)都導(dǎo)出為CSV文件并壓縮
這篇文章主要為大家詳細介紹了如何使用Python將MySQL數(shù)據(jù)庫中所有表的數(shù)據(jù)都導(dǎo)出為CSV文件到一個目錄,并壓縮為zip文件到另一個目錄下,需要的可以了解下2025-03-03
Python基于datetime或time模塊分別獲取當(dāng)前時間戳的方法實例
今天小編就為大家分享一篇關(guān)于Python基于datetime或time模塊分別獲取當(dāng)前時間戳的方法實例,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧2019-02-02

