如何在Java中修复URL中的非法字符?

3
我希望有一个函数可以检测URL中的无效字符,并用其编码等价物替换它们。例如:
ensureValidUrl("http://example.com/invalid url/") // "http://example.com/invalid%20url/"

我曾尝试使用URLEncoder.encode,但它也会对协议进行编码,而这不是我想要的结果。


URI类的多参数构造函数将根据需要转义字符,但是如果你从一个(可能是坏的)预组成的URL开始,这些构造函数可能并不是很有帮助。请注意,new URI(string)不会对字符进行转义。 - VGR
的确,我正在使用完整的URL字符串开始。 - Joaquim d'Souza
1个回答

2
static String getValidURL(String invalidURLString){
    try {
        // Convert the String and decode the URL into the URL class
        URL url = new URL(URLDecoder.decode(invalidURLString, StandardCharsets.UTF_8.toString()));

        // Use the methods of the URL class to achieve a generic solution
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
        // return String or
        // uri.toURL() to return URL object
        return uri.toString();
    } catch (URISyntaxException | UnsupportedEncodingException | MalformedURLException ignored) {
        return null;
    }
}

使用URI和URL类的组合,可以实现您的解决方案。更多关于URLURICharsets的信息。
用法:
System.out.println(getValidURL("http://example.com/invalid url/"));
// http://example.com/invalid%20url/

这看起来很不错!我明天会测试它,非常感谢! - Joaquim d'Souza

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