我有一个 URL,我喜欢用 java 应用程序解析它。 这些 url 可以包含字符,不能通过以下方式调用:
url.openStream()
示例:
https://en.wikipedia.org/w/api.php?format=json&action=query&prop=langlinks&titles=2019–20_coronavirus_pandemic&redirects=&lllimit=400
其中有一个字符 - (2019–20_coronavirus_pandemic),我必须对其进行编码。回复。我想对完整的 URL 进行编码,因为它可能包含其他特殊字符。
我按照以下方式执行此操作,但这对我不起作用:
String urlEncoded = URLEncoder.encode(wikiID, StandardCharsets.UTF_8.toString());
String sURL = "https://en.wikipedia.org" + "/w/api.php?format=json&action=query&prop=langlinks&titles=" + urlEncoded + "&redirects=&lllimit=400";
URL url = new URL(sURL);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
URLEncoder.encode 将 2019–20 编码为 2019%3F20,这是不正确的。不能被调用。 正确的编码是:2019%E2%80%9320
如何正确地通过代码对 url 进行编码?
最佳答案
在上面的代码运行时,您的变量 wikiID
已经损坏。因此,问题出在您未向我们展示的代码中。
为了证明这一点,这里有一个 jshell 中的快速 session 。我使用的是 Windows,因此我使用 Unicode 字符转义 \u2013
作为破折号字符:
jshell> import java.net.URLEncoder;
jshell> import java.nio.charset.StandardCharsets;
jshell> URLEncoder.encode("2019\u20132020_coronavirus_pandemic", StandardCharsets.UTF_8.toString());
$3 ==> "2019%E2%80%932020_coronavirus_pandemic"
jshell> URLEncoder.encode("2019?2020_coronavirus_pandemic", StandardCharsets.UTF_8.toString());
$4 ==> "2019%3F2020_coronavirus_pandemic"
关于java - 如何正确编码以下 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61559025/