您的位置:首页 > 编程语言 > Java开发

java.lang.IllegalArgumentException: Illegal character in scheme at index 0

2015-06-05 23:34 721 查看
有时候,通过httplicent发送url的时候,你会遇到懊恼的java.lang.IllegalArgumentException: Illegal character in scheme at index 0。

你会看到  空格被转成了+号了。 
When to encode space to plus (+) or %20 ...

google 上有解释:

    

URLEncoder not able to translate space character

52
down vote
favorite
8

I am expecting

System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8"));

to output:

Hello%20World


(20 is ASCII Hex code for space)

However, what I get is:

Hello+World


Am I using the wrong method? What is the correct method I should be using?

This behaves as expected. The
URLEncoder
implements the HTML Specifications for how to encode URLs in HTML forms.

From the
javadocs:

This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.

and from the
HTML Specification:

application/x-www-form-urlencoded

Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by `+'

You will have to replace it, e.g.:

System.out.println(java.net.URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20"));

https://www.gotosearch.info/?gws_rd=cr#safe=strict&q=why+urlencoder+change+the+space+to+a+%2B
作为程序员。你做好用google,百度的话,估计找半天找不到一个好答案,google,一般答案就在那里了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息