背景信息分析:

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

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

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

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

我的问题:

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


当前回答

对于我来说,了解区别的关键是了解谁定义资源的ID:

例子(与某些地址服务)

POST (sever creates new resource)

client               server/addresses      // NOTE: no ID in the request
  |                                 |
  | --{POST address data}-->        |
  |                                 |
  | <--{201, created addresses/321} |      // NOTE: resource ID in the reply
  |                                 |
PUT (sever sets data of resource, creating it if necessary)

client               server/addresses/321      // NOTE: *you* put the ID here!
  |                                 |
  | --{PUT address data (to 321)}-->|
  |                                 |
  | <--{201, created }              |          // NOTE: resource ID not required here
  |                                 |

这里有很多很好的答案,下面有很好的细节,但这帮助了我到达这个点。

其他回答

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

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

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

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

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

编辑

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

如果你要提交的话

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

你应该使用邮政方法。

PUT 仅仅是该服务应该从现在开始使用的内容的声明,以便代表客户所识别的资源; POST 是该服务应该从现在开始包含(可能复制)的内容的声明,但服务器如何识别该内容。

PUT x(如果 x 识别一个资源):“用我的内容取代 x 识别的资源的内容。

原始答案(可能更容易阅读):

“拿我给你的东西,把它放在你想要的任何地方,只要你给我它的URL,当你完成。

两者都用于客户端到服务器之间的数据传输,但它们之间存在微妙的差异,即:

PUT POST
Replacing existing resource or creating if resource is not exist. www.example.com/com/customer/{customerId} www.example.com/com/customer/123/order/{orderId} Identifier is chosen by the client. Creating new resources and subordinate resources, e.g. a file is subordinate to a directory containing it or a row is subordinate to a database table. www.example.com/com/customer/ www.example.com/com/customer/123/order/ identifier is returned by server
Idempotent i.e. if you PUT a resource twice, it has no effect. Example: Do it as many times as you want, the result will be same. x=1; POST is neither safe nor idempotent. Example: x++;
Works as specific Works as abstractive
If you create or update a resource using PUT and then make that same call again, the resource is still there and still has the same state as it did with the first call. Making two identical POST requests will most likely result in two resources containing the same information.

类似:

PUT 即采取并放置它在哪里. POST 如发送邮件在邮局。

此分類上一篇

社交媒体/网络分析:

社交媒体上的帖子:当我们发布消息时,它会创建新的帖子(即编辑)我们已经发布的帖子。

添加到上面的所有答案:


在职业生涯中最常用的


我们使用 PUT over POST 在 CREATE 操作中. 为什么? 因为很多在这里也说,答案是不可隐藏的,而 POST 是(要求内容位置和终止)。 我们使用 POST over PUT 在 UPDATE 操作中. 为什么? 因为它破坏了整个包含资源的隐藏副本. 这是有用的,当更新资源。

POST 用于将数据发送到服务器. PUT 用于将数据存入服务器上的资源(例如,文件)。

我看到这一点在一个脚本(第55页)从书HTTP: The Definitive Guide。