When to encode space to plus (+) or ?

前端 未结 5 1673
北恋
北恋 2020-11-22 02:12

Sometimes the spaces get URL encoded to the + sign, some other times to %20. What is the difference and why should this happen?

5条回答
  •  醉梦人生
    2020-11-22 02:56

    Its better to always encode spaces as %20, not as "+".

    It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

    Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".

    I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

    unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
    

提交回复
热议问题