背景信息分析:

根据 RFC 2616,第 9.5 条,POST 用于创建资源:

使用 POST 方法要求原始服务器接受请求中包含的实体作为请求-URI 在请求线中识别的资源的新子属。

根据 RFC 2616,第 9.6 条,PUT 用于创建或取代资源:

PUT 方法要求关闭的实体存储在提供的请求-URI. 如果请求-URI 提到已经存在的资源,关闭的实体 SHOULD 将被视为居住在原始服务器的修改版本. 如果请求-URI 没有指向现有资源,并且 URI 能够由请求用户年龄定义为新资源。

我的问题:

那么,哪种HTTP方法应该用于创建资源?或者两者都应该得到支持?


当前回答

Ruby on Rails 4.0 将使用“PATCH”方法而不是 PUT 进行部分更新。

RFC 5789 讲述了 PATCH (自 1995 年以来):

一个新的方法是必要的,以改善互动性和防止错误. PUT 方法已经定义,以重新编写一个资源与一个完整的新体,并且不能重新使用,以进行部分变更。 否则, proxies 和 cache,甚至客户端和服务器,可能会被混淆的结果操作。 POST 已经使用,但没有广泛的互动性(

“Edge Rails: PATCH 是更新的新主要 HTTP 方法,”它解释。

其他回答

除了其他人提出的差异之外,我想添加另一个。

在 POST 方法中,您可以在表格数据中发送身体参数

在 PUT 方法中,您必须在 x-www-form-urlencoded 中发送身体参数

标题内容类型:应用程序/x-www-form-urlencoded

因此,您不能在 PUT 方法中发送文件或多部分数据。

编辑

内容类型“应用/x-www-form-urlencoded”是不有效的发送大量的二进制数据或包含非ASCII字符的文本. 内容类型“多部分/形式数据”应用于提交包含文件、非ASCII数据和二进制数据的表格。

如果你要提交的话

文件,非ASCII数据,和二进制数据

你应该使用邮政方法。

创建:

可以用 PUT 或 POST 进行如下:

更新:

只能以以下方式与PUT进行:

PUT 将资源更新为现有资源ID 作为识别器,在 / 资源 URI 或收集下。

例子: <-- 一般 - 具体 -> URI: website.example/users/john website.example - 整个网站用户 - 用户的收集 john - 收集的项目,或资源 URI:website.example/users/john/posts/23 website.example - 整个网站用户 - 用户的收集 john - 收集的项目,或资源帖子 - 收集的帖子 john 23

当你使用POST时,你总是提到收藏,所以每当你说:

POST /users HTTP/1.1

POST /users/john HTTP/1.1

它会工作,但你说你想在用户收藏下添加一个资源。

PUT /users/john HTTP/1.1

让我们来介绍一下特区的一些重要部分:

邮件

因此,它在收藏中创造了一个新的资源。

皮特

参考:

这里是一个简单的规则:

到一个 URL 的 PUT 应该用于更新或创建可以位于该 URL 的资源。

POST to a URL should be used to update or create a resource that is located at some other ("subordinate") URL, or is not locatable via HTTP. URL 应该用于更新或创建位于某个其他(“下级”) URL 或无法通过 HTTP 找到的资源。

在实践中,POST为创建资源工作良好.新创建资源的URL应返回位置响应标题.PUT应用于完全更新资源. 请理解这些是设计RESTful API时最好的做法. HTTP规格不限制使用PUT/POST与创建/更新资源的几个限制。

Create => HTTP PUT
Retrieve => HTTP GET
Update => HTTP POST
Delete => HTTP DELETE

事实上, CRUD 操作的 R(选择) 和 D(选择) 可以直接地图到 HTTP 方法 GET 和 DELETE 相应。 然而,混淆在 C(现实) 和 U(更新) 操作中。 在某些情况下,可以使用 PUT 为创建而在其他情况下需要 POST。

基于上述定义,我的使用 HTTP PUT 方法与使用 HTTP POST 方法为 REST 服务是: 使用 HTTP PUT 方法,当:

The client includes all aspect of the resource including the unique identifier to uniquely identify the resource. Example: creating a new employee.
The client provides all the information for a resource to be able to modify that resource.This implies that the server side does not update any aspect of the resource (such as an update date).

The server will provide some information concerning the newly created resource. For example, take a logging system. A new entry in the log will most likely have a numbering scheme which is determined on the server side. Upon creating a new log entry, the new sequence number will be determined by the server and not by the client.
On a modification of a resource, the server will provide such information as a resource state or an update date. Again in this case not all information was provided by the client and the resource will be changing from one modification request to the next. Hence a non idempotent operation.

结论