Home  >  Article  >  Java  >  What to do if the java url is Chinese garbled?

What to do if the java url is Chinese garbled?

angryTom
angryTomOriginal
2019-11-15 09:46:183425browse

What to do if the java url is Chinese garbled?

url Chinese garbled java

1. Transcode the string: newString("xxxxx" .getBytes("iso-8859-1"),"utf-8")

This transcoding method has great disadvantages because it uses the specified character set to encode this String into a byte sequence, and stores the result into a new byte array, then decodes the resulting byte array using the specified character encoding to construct a new String string. In this case, it is possible to encounter a situation where all one Chinese character cannot be decoded. In this way, the previous words will be displayed normally, but the last word may be garbled.

So it is not recommended to use this method.

2. Transcode before passing the parameters, and then transcode them back after receiving the parameters.

There are two ways to do this:

The first one:

Before passing parameters: use java.net. URLEncoder.encode("xxxx","utf-8"), convert Chinese into hexadecimal characters.

After receiving the parameters: Use java.net.URLDncoder.decode("xxxx", "utf-8") to convert hexadecimal characters into Chinese.

What needs to be noted with this method is that after using encode, special characters will appear. At this time, the special characters need to be replaced with the corresponding hexadecimal. Because special characters are also garbled when passed as parameters in the URL path.

Second type:

Before passing parameters: encodeURI(“xxxx”).

After receiving parameters: Use java.net.URLDncoder.decode("xxxx", "utf-8") to convert hexadecimal characters into Chinese.

What needs to be noted in this method is that after using encodeURI to transcode, special characters will appear. At this time, the special characters need to be transcoded, so use encodeURI twice, that is:

encodeURI(encodeURI("xxxx")).

These two transcoding methods are very useful, so it is recommended that everyone use them.

Specific usage:

1. Client:

url=encodeURI(url);

Server:

String linename = new String(request.getParameter(“name”).getBytes(“ISO-8859-1”),“UTF-8”);

2. Client:

url=encodeURI(encodeURI(url)); //用了2次encodeURI

Server:

String linename = request.getParameter(name);
//java : 字符解码
linename = java.net.URLDecoder.decode(linename , “UTF-8”);

php Chinese website, a large number of free Java introductory tutorials, welcome to learn online!

The above is the detailed content of What to do if the java url is Chinese garbled?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn