最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python使用POST方法發(fā)送HTTP請求的15個示例代碼

 更新時間:2026年05月09日 09:48:48   作者:Chief395  
文章提供了15個使用Python的requests庫調(diào)用HTTP接口進行POST請求的示例,包括發(fā)送簡單POST請求,JSON/XML格式請求,文件/二進制數(shù)據(jù)請求等操作,感興趣的小伙伴可以了解下

以下是使用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ù)參考資料中的描述:

  1. application/x-www-form-urlencoded:瀏覽器原生表單默認格式,數(shù)據(jù)被編碼為鍵值對(如key1=value1&key2=value2)。
  2. multipart/form-data:用于文件上傳,數(shù)據(jù)被分為多個部分,每部分包含字段名和內(nèi)容,由邊界符(boundary)分隔。
  3. application/json:將數(shù)據(jù)結(jié)構(gòu)序列化為JSON字符串,目前最流行的API數(shù)據(jù)交換格式。
  4. 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.requesturllib.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.urlencoderequests.post(data=dict)
multipart/form-data文件上傳/混合表單requests.post(files=dict) 自動處理
application/jsonAPI交互(最常用)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)文章

最新評論

阜宁县| 定西市| 景德镇市| 柳州市| 孝义市| 湟源县| 石泉县| 行唐县| 泸西县| 茶陵县| 陇川县| 修水县| 利川市| 乐业县| 林西县| 孝昌县| 福州市| 潮州市| 南丹县| 昭觉县| 新宁县| 晋江市| 社旗县| 鄂尔多斯市| 新巴尔虎右旗| 威海市| 明光市| 无棣县| 福鼎市| 大厂| 延长县| 黔西县| 洛扎县| 河源市| 凌海市| 德格县| 固始县| 金塔县| 姚安县| 阿城市| 曲阜市|