2011-10-02 107 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是一个替代品(免责声明:我是作者)。

相关问题