Skip to content

Instantly share code, notes, and snippets.

@zxhfighter
Last active December 27, 2015 10:39
Show Gist options
  • Save zxhfighter/7312888 to your computer and use it in GitHub Desktop.
Save zxhfighter/7312888 to your computer and use it in GitHub Desktop.
get or post

get请求和post请求对比

get请求

get请求将查询字符串跟随url发送到服务器,类似如下的格式:

/test/demo_form.asp?name1=value1&name2=value2

参数除了一般的英文字母和数字,有时也免不了要传递一些汉字、特殊符号什么的。

但是URL在网络标准RFC-1738中做了硬性规定:

Thus, only alphanumerics, the special characters "$-_.+!*'(),", and reserved characters used for their reserved purposes may be used unencoded within a URL.

这意味着,如果URL中有汉字,就必须编码后使用。但是麻烦的是,RFC 1738没有规定具体的编码方法,而是交给应用程序(浏览器)自己决定。这导致"URL编码"成为了一个混乱的领域。

查询字符串的值如果是:

  • 字母和数字:原样发送
  • 空格:转换成+,也可以用encodeURIComponent进行base64编码成%20
  • 中文和其他字符:base64编码(IE下需要手动调用encodeURIComponent),得出如%E4%BD%E5%A0等格式的字符串,其中%XXXX为该符号以16进制表示的ASCII

一般在IE下对于get请求的url有长度限制(2083字节),实际上HTTP协议规范并没有对url长度进行限制,这个限制是特定的浏览器和服务器对它的限制。

另外一些需要注意的是:

  • get请求能被缓存、记录历史、加入书签
  • get请求不能涉及敏感数据
  • get请求应当只用来接受数据,是幂等的(多次发送和一次发送,结果是一样的)

post请求

post请求将查询字符串内容放在发送请求的消息主体中(body),类似下面的格式:

POST /test/demo_form.asp HTTP/1.1
Host: w3schools.com
    
name1=value1&name2=value2

因此,由于查询字符串没有附加值url上面,post请求无需对查询字符串进行刻意的编码。

post请求没有大小限制,不过其发送数据的大小一般都受限于服务器的接收和处理能力,谁想上传一个2G的文件试试?

关于post请求,还有一些注意点:

  • post请求不能被缓存、记录历史、加入书签
  • post请求比较安全,能够传递敏感数据
  • post请求用来发送数据,能够影响服务器的状态和数据,不是幂等的

参考资料

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment