0

I am trying a simple url encoding that needs to be done for the URL below:

https://example.org/v1/x/y/Quick Brown Fox/jumps/over/

I use the below code:

String url = https://example.org/v1/x/y/Quick Brown Fox/jumps/over/;
url = UrlEncoder.encode(url,"UTF-8");

Ideally, this should provide output like -

https://example.org/v1/x/y/Quick%20Brown%20Fox/jumps/over/

which is the correct encoding. Instead it ends up replacing space with +

Using JDK 11 - I need %20 because I am using Apache HTTP client to send HTTP request and URI does not take + in the URL where spaces are present.

The Cloud Guy
  • 963
  • 1
  • 8
  • 20
  • What is this UrlEncode class? – Joni Aug 06 '20 at 12:47
  • java.net.UrlEncode – The Cloud Guy Aug 06 '20 at 12:50
  • 1
    Do you mean URLEncoder? This one? https://docs.oracle.com/javase/10/docs/api/java/net/URLEncoder.html Can you make sure the code in the question matches the code in your project – Joni Aug 06 '20 at 12:52
  • 2
    The `UrlEncode.encode()` method works as intended, since it implements the encoding for the application/x-www-form-urlencoded MIME format. Check this stackoverflow entry for more details: https://stackoverflow.com/questions/4737841/urlencoder-not-able-to-translate-space-character – Bernard Aug 06 '20 at 12:55

1 Answers1

2

You can use the URI class:

        URI uri = new URI("https", "//example.org/v1/x/y/Quick Brown Fox/jumps/over/", null);
        System.out.println(uri.toASCIIString()); // Should be escaped

Just be aware that you need to handle an URISyntaxException.

Bernard
  • 333
  • 2
  • 8