2011-10-02 20 views

回答

3

我測試了一些庫,包括現在傳統的HTTPClient URIUtil,沒有找到任何可行的解決方案。通常情況下,我已經受夠了這種類型的java.net.URI結構的雖然把成功:

/** 
* Tries to construct an url by breaking it up into its smallest elements 
* and encode each component individually using the full URI constructor: 
* 
* foo://example.com:8042/over/there?name=ferret#nose 
* \_/ \______________/\_________/ \_________/ \__/ 
*  |   |   |   |  | 
* scheme  authority  path  query fragment 
*/ 
public URI parseUrl(String s) throws Exception { 
    URL u = new URL(s); 
    return new URI(
     u.getProtocol(), 
     u.getAuthority(), 
     u.getPath(), 
     u.getQuery(), 
     u.getRef()); 
} 

可以使用下面的常規組合。它重複解碼URL,直到解碼的字符串不變,這對於例如雙編碼可能是有用的。請注意,以保持它的簡單,這個樣本不提供任何故障保護等

public String urlDecode(String url, String encoding) throws UnsupportedEncodingException, IllegalArgumentException { 
    String result = URLDecoder.decode(url, encoding); 
    return result.equals(url) ? result : urlDecode(result, encoding); 
} 
1

我建議不要使用java.net.URLEncoder爲百分號編碼的URI。儘管名稱,它是不是很大網址進行編碼,因爲它不遵循rfc3986標準,而不是編碼到application/x-www-form-urlencoded MIME格式(read more here

對於編碼Scala中的URI,我會建議從噴霧HTTP的Uri類。 scala-uri是一個替代品(免責聲明:我是作者)。

相關問題