我的 Java 独立应用程序从用户那里获得了一个 URL(它指向一个文件),我需要点击它并下载它。我面临的问题是我无法正确编码 HTTP URL 地址...
例子:
URL: http://search.barnesandnoble.com/booksearch/first book.pdf
java.net.URLEncoder.encode(url.toString(), "ISO-8859-1");
返回我:
http%3A%2F%2Fsearch.barnesandnoble.com%2Fbooksearch%2Ffirst+book.pdf
但是,我想要的是
http://search.barnesandnoble.com/booksearch/first%20book.pdf
(空格替换为 %20)
我猜 URLEncoder
不是为编码 HTTP URL 而设计的...JavaDoc 说“用于 HTML 表单编码的实用程序类”...有没有其他方法可以做到这一点?
最佳答案
java.net.URI类可以提供帮助;在您找到的 URL 文档中
Note, the URI class does perform escaping of its component fields in certain circumstances. The recommended way to manage the encoding and decoding of URLs is to use an URI
使用具有多个参数的构造函数之一,例如:
URI uri = new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/first book.pdf",
null);
URL url = uri.toURL();
//or String request = uri.toString();
(URI的单参数构造函数不会转义非法字符)
只有非法字符会被上面的代码转义——它不会转义非 ASCII 字符(参见 fatih 的评论)。
toASCIIString
方法可用于获取仅包含 US-ASCII 字符的字符串:
URI uri = new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/é",
null);
String request = uri.toASCIIString();
对于带有 http://www.google.com/ig/api?weather=São Paulo
之类查询的 URL,请使用 5 参数版本的构造函数:
URI uri = new URI(
"http",
"www.google.com",
"/ig/api",
"weather=São Paulo",
null);
String request = uri.toASCIIString();
关于java - Java中的HTTP URL地址编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/724043/