AdSense

網頁

2019/2/5

HTTP 協議的Idempotent Methods

HTTP/1.1常見的Methods中,屬於Idempotent Methods的如下。


HTTP協議中屬於Idempotent Methods的包括屬於Safe MethodsGETHEADOPTIONSTRACE,以及PUT, DELETE

HTTP Idempotent Methods的意思是,若client發出一次或多次同樣的請求對server的(狀態)影響結果不變,則此請求方法則為Idempotent Methods。也就是說同樣的請求即使不小心送了兩次,也不用擔心對server端造成不同的影響。

Idempotent Methods的目的是若請求失敗可以自動重送而不用擔心造成不同的結果。

節錄RFC7231 - Section 4.2.2

A request method is considered "idempotent" if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request. Of the request methods defined by this specification, PUT, DELETE, and safe request methods are idempotent.


Safe Methods的方法本來就不會在server端造成任何影響,不論請求一次或多次都只是讀取,所以屬於Idempotent Methods。

PUT的作用是完整更新資料,也就是把原有的資料全部取出然後更新,假設今天要修改會員的電話號碼,則先取出原有的會員資料,修改了電話號碼然後送出請求更新,這樣請求不管一次兩次或多次結果都相同,所以屬於Idempotent Methods。

DELETE請求刪除時,假設刪除一筆會員,一定會附加要刪除對象的key,例如會員編號或email,今天送出一次是刪除該會員,若後續再送出同樣的刪除請求,也是刪除該會員,只是可能因為已經被刪除了而沒有任何動作,一次和多次同樣的刪除請求結果相同,所以屬於Idempotent Methods。

POST不屬於Idempotent Methods,因為每一次的請求都會對server端造成新的影響。POST是新增資料,例如購物車,同樣的請求送出一次與兩次的結果是不同的,每一次的請求都會多新增一筆購買產品,所以POST不屬於Idempotent Methods。

PATCH不屬於Idempotent Methods,與PUT的不同在於PATCH並不是把原有的資料全部取出然後針對要更新的部分修改再送回,而僅是送出要修改部分的參數。

節錄RFC 5789 - Section 2

PATCH is neither safe nor idempotent as defined by [RFC2616], Section 9.1.(RFC2616已經過時了,應改看RFC7231 - Section 4.2.1Section 4.2.2


若文章對您有幫助還幫忙點個廣告鼓勵,謝謝您的支持。


沒有留言:

AdSense