import base64

# 定義API的URL
api_url = "http://m.dlbhg.com/v2/scd2023122526402d70e0d9/base64"

# 要編碼的字符串
original_string = "Hello, World!"

# 使用base64編碼
encoded_bytes = base64.b64encode(original_string.encode("utf-8"))
encoded_string = encoded_bytes.decode("utf-8")

# 打印編碼后的字符串
print("Base64編碼后的字符串:", encoded_string)

# 準備請求數據
data = {
"encoded_string": encoded_string
}

# 設置請求頭(如果需要)
headers = {
"Content-Type": "application/json"
}

# 發送POST請求
try:
response = requests.post(api_url, json=data, headers=headers)
response.raise_for_status() # 檢查請求是否成功
except requests.exceptions.HTTPError as errh:
print("HTTP錯誤:", errh)
except requests.exceptions.ConnectionError as errc:
print("連接錯誤:", errc)
except requests.exceptions.Timeout as errt:
print("超時錯誤:", errt)
except requests.exceptions.RequestException as err:
print("請求異常:", err)
else:
# 解析響應
result = response.json()
decoded_string = result.get("decoded_string")
print("解碼后的字符串:", decoded_string)

代碼詳解

1. 導入庫
import requests
import base64
2. 定義API的URL
api_url = "http://m.dlbhg.com/v2/scd2023122526402d70e0d9/base64"

根據要求,使用指定的API路徑。

3. 準備要編碼的字符串
original_string = "Hello, World!"

您可以將original_string替換為任何您想要編碼的字符串。

4. 進行Base64編碼
encoded_bytes = base64.b64encode(original_string.encode("utf-8"))
encoded_string = encoded_bytes.decode("utf-8")
5. 打印編碼后的字符串
print("Base64編碼后的字符串:", encoded_string)

輸出編碼后的結果,便于驗證。

6. 準備請求數據
data = {
"encoded_string": encoded_string
}

構建請求的JSON數據。

7. 設置請求頭(可選)
headers = {
"Content-Type": "application/json"
}

設置請求頭,指定數據類型為JSON。

8. 發送POST請求并處理異常
try:
response = requests.post(api_url, json=data, headers=headers)
response.raise_for_status()
# 后續處理...
except requests.exceptions.HTTPError as errh:
print("HTTP錯誤:", errh)
# 其他異常處理...
9. 解析響應
result = response.json()
decoded_string = result.get("decoded_string")
print("解碼后的字符串:", decoded_string)

運行代碼

1. 保存代碼

將上述代碼保存為base64_api_example.py。

2. 運行代碼

在命令行中,導航到代碼所在的目錄,輸入以下命令:

python base64_api_example.py
3. 查看輸出

如果一切正常,您將看到類似以下的輸出:

Base64編碼后的字符串: SGVsbG8sIFdvcmxkIQ==
解碼后的字符串: Hello, World!

注意事項

base64加解密是否有替換方案?

1. 其他編碼方式

Base32
Base16(十六進制編碼)

2. 加密算法

對稱加密
非對稱加密

3. 哈希函數

4. 序列化格式

5. 其他

選擇的考慮因素

如何找到base64加解密?

冪簡集成是國內領先的API集成管理平臺,專注于為開發者提供全面、高效、易用的API集成解決方案。冪簡API平臺提供了多種維度發現API的功能:通過關鍵詞搜索API、從API Hub分類瀏覽API、從開放平臺分類瀏覽企業間接尋找API等。

上一篇:

使用免費API實時抓取百度熱搜的實戰教程

下一篇:

如何免費調用Kimi API實現項目集成
#你可能也喜歡這些API文章!

我們有何不同?

API服務商零注冊

多API并行試用

數據驅動選型,提升決策效率

查看全部API→
??

熱門場景實測,選對API

#AI文本生成大模型API

對比大模型API的內容創意新穎性、情感共鳴力、商業轉化潛力

25個渠道
一鍵對比試用API 限時免費

#AI深度推理大模型API

對比大模型API的邏輯推理準確性、分析深度、可視化建議合理性

10個渠道
一鍵對比試用API 限時免費