1. 程式人生 > >HTTP-PATCH請求

HTTP-PATCH請求

接觸到RESTful後,在Spring框架的使用過程中我越來越關注HTTP方法,覺得有必要去重新認識所有的HTTP請求方法,特別是PATCH請求,PATCH請求也是為了完成修改資源的任務而存在。下面以菜鳥觀點分析下PATCH請求:

  • PATCH: 也許你常用的HTTP請求方式就是GET、POST,有的人會用過DELETE、PUT,其實在HTTP1.1中提到過更多的方法。PATCH在早期的HTTP文件 RFC2616中提到過 ,但是卻沒有完全定義它,直到2010年的RFC5789規範中才真正定義了新的HTTP1.1方法-PATCH。
  1. The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request- URI. The set of changes is represented in a format called a “patch document” identified by a media type. If the Request-URI does not point to an existing resource, the server MAY create a new resource, depending on the patch document type (whether it can logically modify a null resource) and permissions, etc.The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.

這裡就不列舉出所有PATCH相關的定義了,可以到RFC5789規範中查詢。

HTTP中為了提高互動操作性與防止錯誤,確實需要一種新的修改方法,而PUT方法已經被定義為用一個請求體去修改一個完整的資源。並且不能重複做部分更改,否則代理和快取、託福學習計劃甚至伺服器或者客戶端都會得到有問題的操作結果。 至此,PATCH方法有了被完全定義的必要。 PATCH在請求中定義了一個描述修改的實體集合,如果被請求修改的資源不存在,伺服器可能會建立一個新的資源。

PUT與PATCH的區別反映在伺服器內部修改資源的方式中。

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the origin server, and the client is requesting that the stored version be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it also MAY have side effects on other resources; i.e., new resources may be created, or existing ones modified, by the application of a PATCH.

簡單來說就是:

PATCH方法用於資源的部分內容的更新;

PUT用於更新某個較為完整的資源;

PATCH方法可能會在資源不存在時去建立它。

PUT PATCH
冪等 非冪等
副作用 副作用

PUT與PATCH都可以帶RequestBody請求

  • 實現 Spring與JBoss Netty在後面的版本實現了PATCH方法的支援