2012-09-14 71 views
5

我对Java相当陌生,遇到过这个问题。我试图寻找,但从来没有得到正确的答案。URISyntaxException - 如何处理网址与%

我有例如

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 

当我使用这个网址和火它在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); 

回答

5

还使用%25对百分号进行编码。

http://something.com/test/anything 10%-20% 04-03-07可以与http://something.com/test/anything%2010%25-20%25%2004-03-07一起使用。

您应该能够使用例如URLEncoder.encode对于这一点 - 只要记住,你需要来urlencode路径部分,在此之前没有任何东西,所以像

String encodedUrl = 
    String.format("http://something.com/%s/%s", 
     URLEncoder.encode("test", "UTF-8"), 
     URLEncoder.encode("anything 10%-20% 04-03-07", "UTF-8") 
    ); 

注:URLEncoder的编码空格+而不是%20,但它应该工作得很好,两者都可以。

+0

感谢完美的作品。我试图逃避它。没有从替换角度思考。 – Vish

-1

你可以使用java.net.URI从您的字符串创建URI

String url = "http://something.com/test/anything 10%-20% 04-03-07" 

URI uri = new URI(
    url, 
    null); 
String request = uri.toASCIIString(); 

HttpClient httpclient = new DefaultHttpClient(); 
HttpGet httpget = new HttpGet(request); 
HttpResponse response = httpclient.execute(httpget);