Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java UTF-8 URLEncoder encoding special characters that it shouldn't

Tags:

java

android

I am trying to encode the username and password when logging in my mobile app. I am connecting to an existing API and am supposed to send an encoded username and password. I am using URLEncoder using UTF_8 but it seems to be encoding most special characters. I am comparing the encoded string to the one encoded by Postman (which is the correct version).

Here is my code:

URLEncoder.encode(value, StandardCharsets.UTF_8.toString());

For the string ~!@#$%^&*()_+{}|:<>?"`[]\;',./

In postman it is being encoded as

~!%40%23%24%25%5E%26*()_%2B%7B%7D%7C%3A%3C%3E%3F%22%60%5B%5D%5C%3B'%2C.%2F

while in my app, it is being encoded as

%7E%21%40%23%24%25%5E%26*%28%29_%2B%7B%7D%7C%3A%3C%3E%3F%22%60%5B%5D%5C%3B%27%2C.%2F

As you can see, it is encoding most special characters (The exceptions being ._*)

like image 481
majozu Avatar asked Dec 02 '25 10:12

majozu


1 Answers

Using the static constant UTF_8's toString() method as the character encoding scheme throws java.nio.charset.IllegalCharsetNameException: java.nio.charset.CharsetICU[UTF-8] as the toString() returns "java.nio.charset.CharsetICU[UTF-8]". To get the desired "UTF-8" use displayName() method instead.

After that change your code work's like you wanted in my environment.

like image 78
Célestin Ballevre Avatar answered Dec 05 '25 00:12

Célestin Ballevre