PUT 和POST 是 HTTP 的两个方法(Method),都可以用来向 HTTP 服务器提交数据。似乎用哪个都可以,但其实两者还是有本质的区别的。
网上关于两者区别的文章比较多,但有相当一部分绝对是误导人。所以这次特意查看了 RFC7231,来澄清二者的区别。
首先直接摘出 RFC7231 中的的部分关键原文:
The fundamental difference between the POST and PUT methods is highlighted by the different intent for the enclosed representation. The target resource in a POST request is intended to handle the enclosed representation according to the resource’s own semantics, whereas the enclosed representation in a PUT request is defined as replacing the state of the target resource. Hence, the intent of PUT is idempotent and visible to intermediaries, even though the exact effect is only known by the origin server.
Proper interpretation of a PUT request presumes that the user agent knows which target resource is desired. A service that selects a proper URI on behalf of the client, after receiving a state-changing request, SHOULD be implemented using the POST method rather than PUT.
上面这两段描述的关键词就是“idempotent”(幂等),理解了这个词就理解了二者的本质区别。下面就围绕这个词从以下几个角度分析 PUT
和 POST
的区别。