2017-08-14 1918 views
0

即使我使用requests.put(),服務器也將它的請求識別爲「GET」。request.put()但它請求使用PUT在我的Python上使用GET

這是我的代碼。

import requests 
import json 

url = 'https://api.domain.com/test/partners/digital-pie/users/assignee' 
payload = """ 
{ 
"assignee": { 
"district": "3", 
"phone": "01010001000", 
"carNum": "598865" 
}, 
"deduction": { 
"min": 1000, 
"max": 2000 
}, 
"meta": { 
"unit-label": "1-1-1", 
"year": "2017", 
"quarter": "2" 
} 
} 
""" 

headers = {"content-type": "application/json", "x-api-key": "test_api_dp" } 

r = requests.put(url, data=json.dumps(payload), headers=headers) 

print("status code:", r.status_code) 
print('encoding:', r.encoding) 
print('text:', r.text) 
print('json:', r.json()) 

當我通過wireshark檢查包時,我可以知道我的代碼請求爲「GET」。

wireshark packet

哪個是錯我的代碼?

增加了更多。

我修正了下面的代碼,發現302重定向是通過檢查r.history發生的。 但仍然堅持爲什麼302發生。
當我比較郵差。它顯示正確。

Comparison with postman

除了第2位。 requests variable watch window

+0

'requests.put()'肯定發送'PUT'方法。你確定服務器沒有響應'302'或'303'重定向嗎? –

+0

您在截圖中顯示的GET請求**與您的請求**不符。 PUT進入'/ test/partners/digital-pie/users/assignee',GET用於'/ partners/digital-pie/users/assignee'。我還注意到,該服務器以404請求響應該GET請求。 –

+0

注意:當使用'json = payload'而不是'data'時,不需要使用'json.dumps()'或設置Content-Type'頭。 –

回答

2

你幾乎肯定被重定向。發送PUT請求發送到,但服務器迴應了3xx redirection response code,然後requests隨後發出GET請求。我注意到wireshark屏幕截圖中的路徑與您的代碼中使用的路徑不匹配(/test前綴丟失),進一步增加了發生重定向的證據。

您可以通過查看r.history檢查redirection history(每個條目是另一種反應物),或者設置allow_redirects=False給不給迴應重定向(你得到的第一個反應,沒有別的)。

您可能正在重定向,因爲您的雙重編碼您的JSON有效負載。對於已經是JSON文檔的字符串,不需要使用json.dumps。您正在發送一個JSON字符串,其內容恰好是一個JSON文檔。這幾乎肯定是錯誤的發送。

正確的作法是刪除json.dumps()呼叫,或用字典更換​​

payload = { 
    "assignee": { 
     "district": "3", 
     "phone": "01010001000", 
     "carNum": "598865" 
    }, 
    "deduction": { 
     "min": 1000, 
     "max": 2000 
    }, 
    "meta": { 
     "unit-label": "1-1-1", 
     "year": "2017", 
     "quarter": "2" 
    } 
} 

順便說一句,你會掉,然後使用json關鍵字參數更好;你得到的Content-Type: application/json頭作爲一個額外的好處:

headers = {"x-api-key": "test_api_dp" }  
r = requests.put(url, json=payload, headers=headers) 

再次,這假定​​是一個Python數據結構,在Python字符串JSON文件。

+0

你說得對。我可以找出頁面重定向。 r.history告訴302代碼。 但我仍然不知道爲什麼302重定向。 與郵差相比。它響應正確。 我客人wireshark不顯示https數據包。 – sungyong

+0

@sungyong:不,wireshark無法顯示加密數據。它可能會列出數據包,但無法解密有效負載以顯示HTTP級別的信息。 –

+0

@sungyong:我看不到你發送的是什麼有效載荷。可能是重定向主體包含更多信息,可能檢查'r.history [0] .content'。標題中可能還有線索。這裏沒有足夠的信息能夠診斷任何事情,真的。 –

0

您可以簡單地測試什麼方法與http://httpbin.org

>>> import requests 
>>> r = requests.put('http://httpbin.org/anything') 
>>> r.content 
b'{\n "args": {}, \n "data": "", \n "files": {}, \n "form": {}, \n 
"headers": {\n "Accept": "*/*", \n "Accept-Encoding": "gzip, deflate", 
\n "Connection": "close", \n "Content-Length": "0", \n "Host": 
"httpbin.org", \n "User-Agent": "python-requests/2.18.3"\n }, \n 
"json": null, \n "method": "PUT", \n "origin": "91.232.13.2", \n "url": 
"http://httpbin.org/anything"\n}\n' 

使用正如你所看到的方法是PUT

+0

是的,OP是錯誤的,當你使用'requests.put()'的時候,總是發送一個PUT請求。問題在於他們在wireshark中查看錯誤的請求。 –