URLEncoder.encode() and a whitespace?

夙愿已清 提交于 2019-12-02 04:12:32

问题


I've got a resource on my server named:

some image.png

There's a space in the name. When I type the url into the browser (chrome), it's transforming the space into %20:

some%20.png

WHen I use URLEncoder.encode("some image.png") from my application, I'm getting:

some+image.png

which causes a 404. What's the right way to encode?


回答1:


http://www.permadi.com/tutorial/urlEncoding/

Note that because the character is very commonly used, a special code ( the "+" sign) has been reserved as its URL encoding. Thus the string "A B" can be URL encoded as either "A%20B" or "A+B"

However, your code is probably failing because some parsers/web servers do not handle them equally for base URL portions - and only recognize + = space in the querystring portion




回答2:


IIRC, both + and %20 are valid strings in a URL.

In the path part of the URL + is not reserved[1], and so has no special meaning and does not need to be %-encoded. Therefore, + means literally the + character in the path part of the URL.

In the query part of the URL + is reserved[2], although the purpose is not stated.

However, when using HTML forms the MIME encoding application/x-www-form-urlencoded is used to encode the parameters which (in a HTTP GET request) are included in the query part of the URL[3].

The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". [3]

Sources:

http://www.ietf.org/rfc/rfc2396.txt

[1] Section 3.3

[2] Section 3.4

http://en.wikipedia.org/wiki/Percent-encoding

[3] "The application/x-www-form-urlencoded type"




回答3:


May not be the best solution but you could using path.replace(" ","%20").

As previously stated both "+" and "%20" should work but if "+" does not I think you have to do a manual replace.



来源:https://stackoverflow.com/questions/5130056/urlencoder-encode-and-a-whitespace

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!