有谁知道一个好的 Scala 或 Java 库可以解决格式错误的 URI 中的常见问题,例如包含应该转义但没有转义的字符?
问问题
731 次
2 回答
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);
}
于 2011-10-02T20:32:17.077 回答