-2

I am having to do stupid s**t like this to get urlEncoding to work like other libraries (iOS, Javascript..) because java.net.URLEncoder is buggy or not written to standard encoding:

URLEncoder.encode(normalizeString(str), StandardCharsets.UTF_8.displayName())
                    .replace("+", "%20")
                    .replace("%40", "@")
                    .replace("*", "%2A");

+ and * are not percent encoded while @ is. and...now it's encoding forward slash /. wtf! is there a good explanation for this? Am I using the wrong Charset?

Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
mutable2112
  • 439
  • 4
  • 15
  • 3
    I suggest that you edit your question and provide a [mcve]. That would include literal input to `encode()` (i.e., not `normalizeString(str)`, which nobody knows what it returns), what that `encode()` call returns, and why you think that it is incorrect. IOW, post clear test cases that fail, and perhaps we can help identify the source of the failure. – CommonsWare Nov 13 '17 at 16:57

1 Answers1

1

I think you misunderstood the role of the URLEncoder. The UrlEncoder implements the HTML Specifications for how to encode URLs in HTML forms.

In your case, I think, the library org.apache.commons.text could be a better solution. It offer to you methods to escape characters like you want.

Valentin Michalak
  • 2,089
  • 1
  • 14
  • 27
  • 2
    Thanks, I ended up using Google's Guava lib which is percent encoding as expected `UrlEscapers.urlFragmentEscaper().escape(string)` – mutable2112 Nov 13 '17 at 18:13