天天看点

java url 20,url参数里的空格为何有时会是%20有时会是加号

If enc_type is PHP_QUERY_RFC1738, then encoding is performed per » RFC 1738 and the application/x-www-form-urlencoded media type, which implies that spaces are encoded as plus (+) signs.

If enc_type is PHP_QUERY_RFC3986, then encoding is performed according to » RFC 3986, and spaces will be percent encoded (%20).

根据上述说明,加号或%20,两种数据标准均是RFC定义的参数格式。表单默认是application/x-www-form-urlencoded编码类型时,空格会替换成+号;普通urlencode()方法或浏览器打开的url有空格的,会替换成%20,参数编码的结果里有时会有空格,这点在传参时为何要先urlencode(),才能保证不被上述两种标准搞乱,有些框架会对经过的参数自动做urldecode(),就导致后面流程参数变形,这点也要注意。表单声明为multipart/form-data时,空格的处理应该会保持原样传递。

各编程语言具体的实现上可能会有所不同

PHP7为例

$arr = ['key'=>'a b'];

http_build_query($arr);

key=a+b

urlencode('a b');

a+b

rawurlencode('a b');

a%20b

python3.8 例子

from urllib.parse import urlencode

print(urlencode({"query":"a b"}))

query=a+b

python2.7 例子

from urllib import urlencode

print(urlencode({"query":"a b"}))

query=a+b

Go 1.14.4例子

package main

import (

"fmt"

"net/url"

)

func main() {

fmt.Printf(url.QueryEscape("a b"))

}

a+b