1

I have a file path:

file://///10.10.10.10/Yev Pri - Ru─▒n G├╢z├╝yle Ortado─Яu.pdf

This is shown as:

file://///10.10.10.10/Ye%20Pri%20-%20Ru%E2%94%80%E2%96%92n%20G%E2%94%9C%E2%95%A2z%E2%94%9C%E2%95%9Dyle%20Ortado%E2%94%80%D0%AFu.pdf

within <a/> tag of HTML when I inspect it. I want to generate same string at Java. When I encode it with

URLEncoder.encode(path, StandardCharsets.UTF_8.displayName())

file%3A%2F%2F%2F%2F%2F10.10.10.10%2FYev+Pri+-+Ru%E2%94%80%E2%96%92n+G%E2%94%9C%E2%95%A2z%E2%94%9C%E2%95%9Dyle+Ortado%E2%94%80%D0%AFu.pdf

It seems that browser applies encodeURI(). How can I get the same string with browser?

kamaci
  • 72,915
  • 69
  • 228
  • 366
  • 1
    Possible duplicate of [Java equivalent to JavaScript's encodeURIComponent that produces identical output?](https://stackoverflow.com/questions/607176/java-equivalent-to-javascripts-encodeuricomponent-that-produces-identical-outpu) – Karl Reid Jun 16 '17 at 14:34
  • @KarlReid thanks for the link. However that answers don't apply to my question. This is a URL path and `/` are not encoded by browser? – kamaci Jun 16 '17 at 14:49
  • Fair enough, sorry. It looks like @VGR's answer here does what you need. – Karl Reid Jun 16 '17 at 14:53

1 Answers1

3

URLEncoder is for encoding form data. To create an escaped URL or URI, use the java.net.URI class:

URI uri = new URI("file", "///10.10.10.10/Yev Pri - Ru─▒n G├╢z├╝yle Ortado─Яu.pdf", null);
String escapedURI = uri.toASCIIString();

Note: You cannot use new URI("file://///10.10.10.10/Yev Pri - Ru─▒n G├╢z├╝yle Ortado─Яu.pdf") because that constructor does not perform percent-escaping of characters which may not legally appear directly in URIs. The class documentation explicitly specifies that the one-argument constructor expects the argument to already have proper escaping.

VGR
  • 40,506
  • 4
  • 48
  • 63
  • So, I cannot use this as answer? – kamaci Jun 16 '17 at 15:02
  • 1
    You can use the URI constructor that takes *three* arguments, as my code block uses. You cannot use the URI constructor that takes one argument. – VGR Jun 16 '17 at 15:03