7

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

4

2 回答 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 回答
1

我建议不要使用java.net.URLEncoder百分比编码 URI。尽管有这个名字,但它并不适合编码 URL,因为它不遵循rfc3986标准,而是编码为application/x-www-form-urlencodedMIME 格式(在此处阅读更多信息

对于在 Scala 中编码 URI,我会推荐来自 spray-http的Uri类。scala-uri是另一种选择(免责声明:我是作者)。

于 2014-02-23T17:40:01.753 回答