The difference between PUT and POST methods-compare POST and PUT methods

PUT vs POST - Comparing HTTP Methods

PUT vs POST

There are various HTTP methods, and each method serves a different purpose. The most commonly used HTTP method is the GET method, which is used to retrieve data from a web server. For example, if you want to load an image from a specific website, the browser will use the following command to make a request to the web server:

GET https://website.com/path/to/image.jpg

However, in addition to GET requests, there are other types of http methods, as follows:

  • HEAD
  • POST
  • PUT
  • DELETE
  • CONNECT
  • OPTIONS
  • TRACE

There are two methods we often get confused when we use them, when to use which one. These two methods are PUT and POST. In this article, we will specifically discuss the difference between PUT and POST and how we should use each method correctly.

2. What does the PUT method do?

The PUT method will completely replace the resources under the target URL, regardless of whether there are resources under the target URL. Using this method, you can create a new resource or overwrite an existing resource, provided you know the exact request URI. An example of using the PUT method to create a new resource is as follows:

PUT /forums/<new_thread> HTTP/2.0
Host: yourwebsite.com

Where <new_thread> is the actual name or ID number of the thread. Alternatively, the PUT method for overwriting existing resources can be as follows:

PUT /forums/<existing_thread> HTTP/2.0
Host: yourwebsite.com

In short, the PUT method is used to create or overwrite resources under the specified URL recognized by the browser.

3. What does the POST method do?

The POST method is used to send user-generated data to the web server. For example, when a user comments on the forum or uploads an avatar, then the POST method should be used. If you don't know where the newly created resource should reside and there is no definite URL, then you should also use the POST method. In other words, if a new forum thread is created and the thread path is not specified, then you can use the following:

POST /forums HTTP/2.0
Host: yourwebsite.com

Using this method, the origin server will return the URL path, and you will receive a response similar to the following:

HTTP/2.0 201 Created
Location: /forums/<new_thread>

In short, the POST method should be used to create a subordinate (or child) resource identification through the request URI. In the above example, according to the source definition, the request URI is /forumsand the subordinate or child should be<new_thread>

4. When is it used?

  1. When you know the URL of the content you want to create or overwrite, you should use the PUT method.
  2. When you only know the URL of the category or subpart of the object to be created, use the POST method.

The article comes from a foreign blog

Guess you like

Origin blog.csdn.net/qq_41800366/article/details/108792197