我对Java相当陌生,遇到了这个问题。我尝试搜索,但从未得到正确答案。
例如,我有一个字符串
String name = anything 10%-20% 04-03-07
现在我需要用这个字符串名称构建一个 url 字符串,如下所示。
http://something.com/test/anything 10%-20% 04-03-07
我尝试用 %20 替换空格,现在我得到了新的 url
http://something.com/test/anything%2010%-20%%2004-03-07
当我使用这个 url 并在 firefox 中触发它时,它工作得很好,但是在 Java 中处理它显然是抛出
Exception in thread "main" java.lang.IllegalArgumentException
at java.net.URI.create(Unknown Source)
at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
Caused by: java.net.URISyntaxException: Malformed escape pair at index 39 :
at java.net.URI$Parser.fail(Unknown Source)
at java.net.URI$Parser.scanEscape(Unknown Source)
at java.net.URI$Parser.scan(Unknown Source)
at java.net.URI$Parser.checkChars(Unknown Source)
at java.net.URI$Parser.parseHierarchical(Unknown Source)
at java.net.URI$Parser.parse(Unknown Source)
at java.net.URI.<init>(Unknown Source)
... 6 more
这是代码抛出错误
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);