The java.net.URI课堂可以提供帮助;在您找到的 URL 文档中
请注意,URI 类在某些情况下确实会执行其组件字段的转义。管理 URL 编码和解码的推荐方法是使用 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 的评论)。
The toASCIIString
方法可用于获取仅包含 US-ASCII 字符的字符串:
URI uri = new URI(
"http",
"search.barnesandnoble.com",
"/booksearch/é",
null);
String request = uri.toASCIIString();
对于带有类似查询的 URLhttp://www.google.com/ig/api?weather=São Paulo
,使用构造函数的 5 参数版本:
URI uri = new URI(
"http",
"www.google.com",
"/ig/api",
"weather=São Paulo",
null);
String request = uri.toASCIIString();