How can I convert a string to a url string?

I want to convert a string to the url version of that string. For example:

The quick brown fox jumps over the lazy dog

to

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

Obviously in this example I could just replace space with %20, but I'd like it to work with more complex input strings too, for example with symbols. Here's how I'm doing it right now, but it's very slow:

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;
        }
    }

This is just using htmlunit to search google with the string and then get back the string from the url, but there has to be a better way. This method is very slow because of creating the webclient and searching google. How do I do it better?


Solution 1:

You can use the URLEncoder class for this. https://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html

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