2012-09-14 35 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);