如何解析动态字符串值以创建URL实例?我需要用空格,重音符号,非ASCII字符替换空格……?
我试图使用URLEncoder,但它也编码/字符,如果我将一个用URLEncoder编码的字符串给URL构造函数,我得到一个MalformedURLException(没有协议).
解决方法:
URLEncoder具有非常误导性的名称.它是根据Javadocs使用的MIME格式参数使用MIME类型application / x-www-form-urlencoded.
据说这可以用于编码例如查询参数.例如,如果参数看起来像& /?#,则其编码的等效项可用作:
String url = "http://host.com/?key=" + URLEncoder.encode("&/?#");
The recommended way to manage the encoding and decoding of URLs is to use URI
以下示例
new URI("http", "host.com", "/path/", "key=| ?/#ä", "fragment").toURL();
生成结果http://host.com/path/?key = | ?/#A#片段.请注意如何编码诸如?& /之类的字符.
编辑
由于您的输入是字符串URL,因此使用URI的参数化构造函数之一将无法帮助您.你也不能直接使用新的URI(strUrl),因为它没有引用URL参数.
所以在这个阶段我们必须使用技巧来获得你想要的东西:
public URL parseUrl(String s) throws Exception {
URL u = new URL(s);
return new URI(
u.getProtocol(),
u.getAuthority(),
u.getPath(),
u.getQuery(),
u.getRef()).
toURL();
}
在使用此例程之前,必须清理字符串以确保它表示绝对URL.我看到两种方法:
>猜猜.将http://添加到字符串中,除非它已经存在.
>使用new URL(URL context, String spec)从上下文构造URI
标签:java,encoding,url,parsing,urlencode
来源: https://codeday.me/bug/20190926/1818557.html