简体   繁体   English

Java UTF-8 URLEncoder 编码它不应该的特殊字符

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

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.我正在连接到一个现有的 API,应该发送一个编码的用户名和密码。 I am using URLEncoder using UTF_8 but it seems to be encoding most special characters.我正在使用使用 UTF_8 的 URLEncoder,但它似乎对大多数特殊字符进行编码。 I am comparing the encoded string to the one encoded by Postman (which is the correct version).我正在将编码的字符串与 Postman 编码的字符串(这是正确的版本)进行比较。

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 ._*)如您所见,它对大多数特殊字符进行编码(例外是 ._*)

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]".使用静态常量UTF_8toString()方法作为字符编码方案会抛出java.nio.charset.IllegalCharsetNameException: java.nio.charset.CharsetICU[UTF-8]作为toString()返回“java.nio.charset.字符集ICU[UTF-8]”。 To get the desired "UTF-8" use displayName() method instead.要获得所需的“UTF-8”,请改用displayName()方法。

After that change your code work's like you wanted in my environment.之后,更改您的代码工作就像您在我的环境中想要的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM