关于url转编码的问题

来源:互联网 发布:mac黄皮适合口红颜色 编辑:程序博客网 时间:2024/06/13 10:27

关于url转编码



1.

java.lang.IllegalArgumentException: Illegal character in query at index 141




url的filename里有殊字符(空格),转换fileName= filename.replaceAll(" ", "%20");



2.



757
down voteaccepted

URLEncoder should be the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.

String q = "random word £500 bank $";String url = "http://example.com/query?q=" + URLEncoder.encode(q, "UTF-8");

Note that spaces in query parameters are represented by +, not %20, which is legitimately valid. The %20 is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?), not in query string (the part after ?).

Also note that there are two encode() methods. One without charset argument and another with. The one without charset argument is deprecated. Never use it and always specify the charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.

All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

See also:

  • What every web developer must know about URL encoding

原创粉丝点击