用于修复格式错误的URI的Scala或Java库

Eri*_*cht 7 java uri scala malformed

有没有人知道一个好的Scala或Java库可以解决格式错误的URI中的常见问题,例如包含应该被转义但不是的字符?

Joh*_*erg 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());
}
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)