PUT和POST的区别

548 阅读1分钟

什么是PUT请求?

PUT method is used to update resource available on the server. Typically, it replaces whatever exists at the target URL with something else. You can use it to make a new resource or overwrite an existing one. PUT requests that the enclosed entity must be stored under the supplied requested URI (Uniform Resource Identifier).

什么是POST请求?

POST is a method that is supported by HTTP and depicts that a web server accepts the data included in the body of the message, which is requested. POST is often used by World Wide Web to send user generated data to the web server or when you upload file.

关键的不同点

PUT method is called when you have to modify a single resource while POST method is called when you have to add a child resource. PUT method response can be cached but you cannot cache PUT method responses. You can use UPDATE query in PUT whereas you can use create query in POST. In PUT method, the client decides which URI resource should have, and in POST method, the server decides which URI resource should have. PUT works as specific while POST work as abstract. If you send the same PUT request multiple times, the result will remain the same but if you send the same POST request multiple times, you will receive different results. PUT method is idempotent whereas POST method is not idempotent.

PUT的例子

Here is the webserver example of a PUT method:

HTTP PUT www.google.com/users/234 HTTP PUT www.google.com/users/234/a…

请求

PUT /new.html HTTP/1.1
Host: example.com
Content-type: text/html
Content-length: 20

<p>New File</p>

响应

If the target resource having current representation and is modified with the state of the enclosed representation, then the server should send two responses. The first response code is 200 (OK), and the second response code is 204 (No Content).

If the target resource does not have any representation, then the server should inform the user by sending a 201 code (Created) response.

 HTTP/1.1 201 Created
 Content-Location: /new.html

POST的例子

HTTP POST www.google.com/users HTTP POST www.google.com/users/234/a…

A form using the default application/x-www-form-urlencoded content type:

POST /test HTTP/1.1
Host: abc.example
Content-Type: application/x-www-form-urlencoded
Content-Length: 40

field1=value1&field2=value2

POST和PUT的区别

Here is the important difference between PUT and POST method:

区别