我試圖用一個Python腳本替換下面的curl命令:
curl --request POST
--url https://xx.com/login
--header 'Content-Type: application/json'
--data '{
"email": "[email protected]",
"password": "PASSWORD"
}'
我嘗試的腳本:
import urllib.request
import json
body = {"email": "[email protected]","密碼": "xxx"}。
myurl = "https://xx.com/login"。
req = urllib.require.Request(myurl)
req.add_header('Content-Type'/span>, 'application/json; charset=utf-8'/span>)
jsondata = json.dumps(body)
jsondataasbytes = jsondata.encode('utf-8') # 需要是位元組數。
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)
當我試圖運行這個腳本時,它沒有給我任何回報,而是顯示已處理完畢。我的代碼邏輯是否正確?還是我的代碼有問題?
uj5u.com熱心網友回復:
對于HTTP和HTTPS的URL,urllib.request.urlopen函式回傳一個http.client.httpResponse物件。它有不同的屬性和方法,你可以使用。
例如,
HTTPResponse.read([amt]) - 讀取并回傳回應體,或者下一個amt位元組。
HTTPResponse.getheaders() - 回傳一個(header, value)tuples的串列。
HTTPResponse.status - 由服務器回傳的狀態代碼。
所以在你的案例中,你可以使用status屬性來檢查狀態。如果它是成功的,使用read方法讀取回應體。
status_code = response.status
如果 status_code == 200: # 請求成功
response_body = response.read() # 這將是位元組物件
response_body_as_string = response_body.decode('utf-8')
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/331030.html
標籤:
