【问题标题】:How can I convert a string to a url string?如何将字符串转换为 url 字符串?
【发布时间】:2022-01-15 10:34:49
【问题描述】:

我想将一个字符串转换为该字符串的 url 版本。例如:

敏捷的棕狐跳过懒惰的狗

%20quick%20brown%20fox%20jumps%20over%20the%20lazy%20dog

显然在这个例子中我可以用 %20 替换空格,但我希望它也能处理更复杂的输入字符串,例如符号。这是我现在的做法,但速度很慢:

public static String toURLString(String str)
    {
        try
        {
            WebClient webClient = new WebClient();
            HtmlPage page = webClient.getPage("https://www.google.com/search?q=" + str);
            String prefix = "https://www.google.com/search?q=";
            String tokens = page.getUrl().toString().substring(prefix.length());
            webClient.close();
            return tokens;
        } catch (FailingHttpStatusCodeException | IOException e)
        {
            e.printStackTrace();
            return null;
        }
    }

这只是使用 htmlunit 用字符串搜索 google,然后从 url 中取回字符串,但必须有更好的方法。由于创建 webclient 和搜索 google,此方法非常慢。我怎样才能做得更好?

【问题讨论】:

    标签: java html htmlunit


    【解决方案1】:

    您可以为此使用URLEncoder 类。 https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html

    URLEncoder.encode("Your String here", StandardCharsets.UTF_8);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 2012-05-16
      • 1970-01-01
      • 2018-04-30
      • 2014-05-26
      • 1970-01-01
      相关资源
      最近更新 更多