我测试了一些库,包括现在遗留的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());
}
Run Code Online (Sandbox Code Playgroud)
可以与以下例程结合使用。它重复解码 anURL
直到解码的字符串不改变,这对于例如双重编码很有用。请注意,为了简单起见,此示例不具有任何故障保护等功能。
public String urlDecode(String url, String encoding) throws UnsupportedEncodingException, IllegalArgumentException {
String result = URLDecoder.decode(url, encoding);
return result.equals(url) ? result : urlDecode(result, encoding);
}
Run Code Online (Sandbox Code Playgroud)