1. 程式人生 > >HTTP中GET和POST對比

HTTP中GET和POST對比

HTTP中GET和POST對比

0x01 摘要

網上有不少文章直接拿出結論即GET比POST快,但是POST比GET安全,卻沒有給出詳細的解釋,我查了一些資料同大家分享下。

0x02 效率

  • GET操作有快取,可以使多次客戶端相同請求值會對伺服器傳送一個請求。
  • POST的header和body會分兩次提交 -> 暫未證實

0x03 安全性

  • GET相較而言不安全,因為GET請求一般來說引數就是在URL裡,很容易被他人獲取,還有可能被放入瀏覽器歷史記錄,非常容易洩露敏感資訊。

  • 而POST的引數放在請求體裡面。

0x04 長度限制

  • 雖然HTTP協議沒有規定,但是主流瀏覽器和伺服器都對GET方法URI長度進行了自己的限制,所以某些場景必須使用POST
  • HTTP協議也沒有規定POST長度,但是一般可調整伺服器配置的POST長度限制,一般比GET大,而且有些資料格式只能用POST比如檔案

0x05 可靠性

  • 多數瀏覽器對於POST請求採取兩階段傳送:header->body。這就導致了一些額外的傳輸開銷和意外情況發生的可能性

0x06 快取

  • GET請求會被快取
  • POST請求不進行快取

0x07 冪等

  • GET請求是冪等的,也就是說一般GET請求無論執行多少次結果都應該相同,不應該改變資料庫。比如持續重新整理時不會造成使用者自己填寫的資料變更時。比如瀏覽新聞網站,百度首頁等。再比如搜尋時(因為搜尋操作一般不會改變資料庫)。
  • POST請求非冪等,操作會對資料庫造成影響。比如寫了一篇部落格,或者填寫了一些註冊資訊,此時應該用POST請求提交,不能重新整理。
    There are several misconceptions about GET and POST in HTTP. There is one primary difference, GET must be idempotent while POST does not have to be. What this means is that GETs cause no side effects, i.e I can send a GET to a web application as many times as I want to (think hitting Ctrl+R or F5 many times) and the requests will be ‘safe’

I cannot do that with POST, a POST may change data on the server. For example, if I order an item on the web the item should be added with a POST because state is changed on the server, the number of items I’ve added has increased by 1. If I did this with a POST and hit refresh in the browser the browser warns me, if I do it with a GET the browser will simply send the request.

On the server GET vs POST is pure convention, i.e. it’s up to me as a developer to ensure that I code the POST on the server to not repeat the call. There are various ways of doing this but that’s another question.

To actually answer the question if I use GET or POST to perform the same task there is no performance difference.

You can read the RFC for more details.

0x08 適用性

  • 使用POST時,一般可以用來做一些增刪改之類的操作,因為不能直接在瀏覽器輸入就操作
  • 而GET操作對應的連線應該足夠安全。比如某個GET地址對應是刪除某個使用者資訊,那應該出現一個確認的頁面,而不是直接刪除,否則很容易誤操作。

0x09 總結

  • 如果資料變更少,引數少,資料量小,安全級別低(不怕被存入歷史記錄),可以使用HTTP GET。
  • 高安全操作如增刪改查,上傳下載檔案等,可以使用HTTP POST。在RESTful應用程式中,POST通常會被覆蓋以提供PUT和DELETE呼叫。

0xFF 參考文件

How to: Choose between HTTP POST and HTTP GET requests for ASP.NET AJAX Endpoints

Why GET method is faster than POST in HTTP?

When do you use POST and when do you use GET?

URIs, Addressability, and the use of HTTP GET and POST

GET傳參最大長度的理解誤區

關於 HTTP GET/POST 請求引數長度最大值的一個理解誤區