情況
我們有一個java的服務端
使用代碼如下:
@PutMapping("/api/updateMsg")
public ResponseEntity<MyObject> putMyObject(
@RequestBody MyObject myObject) {
...
}
提供的api地址如下:
http://127.0.0.1:8080/api/updateMsg
然後在python代碼中 調用這個api如下:
import requests
import json
url_put = "http://127.0.0.1:8080/api/updateMsg"
headers_put = {
'Content-Type': "application/json"
}
param = {
'myObjectField': 'hello'
}
payload = json.dumps(param)
response_put = requests.put(url, data=payload, headers=headers_put)
報錯如下:
request method get not support
原因
這裏有個很奇怪的現象,我們在python中明明已經使用了 put方法,但是 服務端接收時還是 識別爲get請求。
原因是因爲 requests.put 請求url時,這個請求被302重定向了.
發送PUT請求發送到,但服務器迴應了3xx redirection response code,requets 庫會自動處理了重定向請求了(默認allow_redirects=True 是自動處理重定向),但是 發出的請求是get的方式。所以requests隨後發出GET請求。
解決方案
我們首先需要校驗下 是不是受