天天看點

什麼時候用GET?什麼時候用POST?

前些天發現了一個巨牛的人工智能學習網站,通俗易懂,風趣幽默,忍不住分享一下給大家。點選跳轉到教程。

一、

GET和POST兩種方法都是将資料送到伺服器,但你該用哪一種呢?

HTTP标準包含這兩種方法是為了達到不同的目的。POST用于建立資源,資源的内容會被編入HTTP請示的内容中。例如,處理訂貨表單、在資料庫中加入新資料行等。

當請求無副作用時(如進行搜尋),便可使用GET方法;當請求有副作用時(如添加資料行),則用POST方法。一個比較實際的問題是:GET方法可能會産生很長的URL,或許會超過某些浏覽器與伺服器對URL長度的限制。

若符合下列任一情況,則用POST方法:

* 請求的結果有持續性的副作用,例如,資料庫内添加新的資料行。

* 若使用GET方法,則表單上收集的資料可能讓URL過長。

* 要傳送的資料不是采用7位的ASCII編碼。

若符合下列任一情況,則用GET方法:

* 請求是為了查找資源,HTML表單資料僅用來幫助搜尋。

* 請求結果無持續性的副作用。

* 收集的資料及HTML表單内的輸入字段名稱的總長不超過1024個字元。

二、

最近開到一段W3的資料,寫的不錯,原文位址如下:http://bu-choreography.iteye.com/admin/blogs/new。翻譯總結如下: 

快速判斷: 

如下情況使用GET方法:用戶端與服務端的互動像是一個提問(如查詢操作、搜尋操作、讀操作) 

如下情況使用POST方法: 

       1.互動是一個指令或訂單(order),比提問包含更多資訊 

       2.互動改變了伺服器端的資源并被使用者察覺,例如訂閱某項服務 

       3.使用者需要對互動産生的結果負責 

聽起來稍微明白了一點,接着來。 

根據HTTP協定規定,GET方法可以攜帶互動需要的所有資料,是以你會看到搜尋百度或谷歌的時候,點選搜尋形成的URL包含了你剛才的搜尋關鍵字,沒有安全需求的請求把資訊放URL裡沒關系,但是你通路銀行網站的時候,不希望把賬戶、密碼這些放在URL裡被人攔截是吧,是以HTTP設計了POST請求,他可以把請求資訊放在HTTP請求裡,具體格式這裡不細說了,這樣你就不能簡單的從URL裡找到賬戶、密碼了。 

講完這些,是不是比較清楚了呢。 

文章還例舉了幾個曾經的HTTP請求限制。 

1.URI不能超過256個字元。這個限制在有些伺服器裡是存在的,有的伺服器為了網絡安全,為了防止拒絕式攻擊會把URL字元限制在4000字元 

2.你送出了GET請求,又馬山按了backspace鍵,會導緻get方法被重新執行 

3.你在一個頁面使用了安全協定,跳轉到了另一個使用不安全協定的頁面時,會導緻安全資料洩漏給第二個頁面。

以上一中内容摘自《Web Database Application with PHP and MySQL, 2nd Edition》一書,中文版《PHP & MySQL Web資料庫應用開發指南》。英文原文内容如下: 

GET versus POST

Both the GET and POST methods send data to the server, but which method should you use?

The HTTP standard includes the two methods to achieve different goals. The POST method was intended to create a resource. The contents of the resource would be encoded into the body of the HTTP request. For example, an order form might be processed and a new row in a database created.

The GET method is used when a request has no side effects (such as performing a search) and the POST method is used when a request has side effects (such as adding a new row to a database). A more practical issue is that the GET method may result in long URLs, and may even exceed some browser and server limits on URL length.

Use the POST method if any of the following are true:

* The result of the request has persistent side effects such as adding a new database row.

* The data collected on the form is likely to result in a long URL if you used the GET method.

* The data to be sent is in any encoding other than seven-bit ASCII.

Use the GET method if all the following are true:

* The request is to find a resource, and HTML form data is used to help that search.

* The result of the request has no persistent side effects.

* The data collected and the input field names in a HTML form are in total less than 1,024 characters in size.