java - Java中的HTTP URL地址编码

标签 java http urlencode

我的 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/

相关文章:

http - 在不发送第一个 POST 的情况下 curl 重定向

javascript - 为什么请求接受: */* when the browser is asking for a javascript file?

javascript - 编码uri组件,不自动解码

java - 是否可以在 Java 中动态构建多维数组?

java - 在每个线程之间分配数字范围

spring - HTTP 使用 RestTemplate 获取 header

javascript - 在 JavaScript 中编码 URL?

linux - 使用 SharePoint URL 和 cURL 进行 URL 编码

java - 在围绕屏幕移动球的情况下,如何正确处理 JComponent 的按键和重绘?

java - 如何避免耦合两个现在具有相似实现但将来可能会发生变化的方法?