Scala或Java库用于修复格式不正确的URI

7

有没有好的Scala或Java库可以修复常见的URI格式问题,例如包含应该被转义但未转义的字符?

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);
}

1
我建议不要使用java.net.URLEncoder进行百分号编码URI。尽管名称是这样,但它不适用于编码URL,因为它不遵循rfc3986标准,而是编码为application/x-www-form-urlencoded MIME格式(在此阅读更多信息
对于在Scala中编码URI,我建议使用spray-http中的Uri类。 scala-uri是一种替代方法(免责声明:我是作者)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接