Home > Blockchain >  How can I convert a string to a url string?
How can I convert a string to a url string?

Time:01-15

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 quick brown fox jumps over the lazy dog

Obviously in this example I could just replace space with , 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?

CodePudding user response:

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);
  •  Tags:  
  • Related