http - PATCH 和 PUT 请求之间的主要区别是什么?

标签 http patch put http-verbs

我在我的 Rails 应用程序中使用 PUT 请求。现在,浏览器实现了一个新的 HTTP 动词 PATCH。所以,我想知道 PATCHPUT 请求之间的主要区别是什么,以及我们何时应该使用其中之一。

最佳答案

HTTP 动词可能是 HTTP 协议(protocol)中最神秘的东西之一。它们存在,而且数量很多,但它们为什么存在?

Rails 似乎想要支持许多动词,并添加一些 Web 浏览器本身不支持的动词。

这里是 http 动词的详尽列表:http://annevankesteren.nl/2007/10/http-methods

来自官方 RFC 的 HTTP 补丁:https://datatracker.ietf.org/doc/rfc5789/?include_text=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 动词没有像在 rails 应用程序中那样使用...据我了解,RFC 补丁动词应该用于发送补丁指令,就像你在两个文件之间做一个差异。您无需再次发送整个实体,而是发送一个比重新发送整个实体小得多的补丁。

假设您要编辑一个巨大的文件。您编辑 3 行。您无需发送回文件,只需发送差异即可。从好的方面来说,发送补丁请求可用于异步合并文件。版本控制系统可能会使用 PATCH 动词来远程更新代码。

另一个可能的用例与 NoSQL 数据库有些相关,可以存储文档。假设我们使用 JSON 结构从服务器向客户端来回发送数据。如果我们想删除一个字段,我们可以使用类似于 mongodb 中 $unset 的语法。 .其实mongodb更新文档的方法大概可以用来处理json补丁。

以这个例子为例:

db.products.update(
   { sku: "unknown" },
   { $unset: { quantity: "", instock: "" } }
)

我们可以有这样的东西:

PATCH /products?sku=unknown
{ "$unset": { "quantity": "", "instock": "" } }

最后但同样重要的是,人们可以随心所欲地谈论 HTTP 动词。只有一个真相,真相就在 RFC 中。

关于http - PATCH 和 PUT 请求之间的主要区别是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21660791/

相关文章:

git-apply 神秘地失败了,我该如何排除故障/修复?

java - 如何在java中使用http put请求将本地文件发送到云组织?

python - Python 和 Tomcat 之间缺少 PUT 变量

c# - Servicestack FallbackRoute 无法识别尾部斜线

python - 如何在使用 mark.parametrize 装饰器的同时使用补丁装饰器?

PHP CURL DELETE 请求

mercurial - Mercurial 可以做反向补丁吗?

java - 如何在 Java 中使用 JSONObject 设置整数值?

.net - WCF - 进行多次调用时随机客户端超时

json - 如何使用浏览器进行基本的 REST API 调用