【问题标题】:How to encode following URL correctly如何正确编码以下 URL
【发布时间】:2020-05-02 12:00:55
【问题描述】:

我有一个我喜欢通过 java 应用程序解析的 URL。 这些 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?

【问题讨论】:

    标签: java url encoding


    【解决方案1】:

    您的变量wikiID 在上面的代码运行时已经损坏。因此,问题在于您没有向我们展示的代码。

    为了证明这一点,这里有一个 jshell 中的快速会话。我在 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"
    

    【讨论】:

      猜你喜欢
      • 2018-09-20
      • 2016-11-28
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2019-03-27
      相关资源
      最近更新 更多