[Python] 如何用 Python3 傳送POST請求 和 得到回應

英文標題: How to Request Post and Get Response by Python3

網路上教學其實挺多的
不過大多都是給Python2使用

雖說Python3的官方有範例
不過使用起來有問題



<官方範例程式碼+我的說明>
import http.client, urllib.parse
params = urllib.parse.urlencode({'@number': 12524, '@type': 'issue', '@action': 'show'}) #要給的參數
headers = {"Content-type": "application/x-www-form-urlencoded", #要給的Headers
           "Accept": "text/plain"}
conn = http.client.HTTPConnection("bugs.python.org") #執行HTTP連線,需要做urlencode
conn.request("POST", "", params, headers) #發送POST請求
"""
根據官方doc說法,request的第二個參數是輸入url
我看別人的用法是可以把子目錄放在url那裡

e.g.
在www.test.org這個網域下面有sub這個指目錄
那就可以在url下: /sub
這樣就會對"www.test.org/sub"這網址下POST請求
"""

response = conn.getresponse() #得到回應並儲存在response
print(response.status, response.reason)

data = response.read()
data
conn.close()
參考: https://docs.python.org/3.2/library/http.client.html

會得到400 bed request
我也不知道是怎麼回事

然後我在舊版本的document找到可以用的:
 <官方範例程式碼-修改版>
import urllib.request
import urllib.parse
params = urllib.parse.urlencode({'name': '基隆市'}) #這是我自己的參數
params = params.encode('UTF-8') #這裡很重要,沒有encode會有error
f = urllib.request.urlopen(your url, params)
print(f.read())
參考:https://docs.python.org/3.0/library/urllib.request.html

之後我會再研究看看是python問題還是我的restful server有問題。

<測試環境>
Python: 3.4.2
API Server: Slim2.3.5+PHP5.6+Apache(unknown) in Windows 7 64bit

TAG: post

留言

這個網誌中的熱門文章

[Javascript] 利用Google Calendar api 存取 Google 行事曆

[滑鼠] 羅技G402 換微動