如何将字符串转换为 url 字符串?

How can I convert a string to a url string?

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

The quick brown fox jumps over the lazy dog

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

显然,在此示例中,我可以将 space 替换为 %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,此方法非常慢。我怎样才能做得更好?

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

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