Home  >  Article  >  Java  >  Solution to garbled url in java

Solution to garbled url in java

尚
Original
2019-12-03 10:29:282526browse

Solution to garbled url in java

Solution to garbled url in java: (Recommended: java video tutorial)

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 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, you may encounter the situation that you cannot decode all the Chinese characters. 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 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: Character decoding

linename = java.net.URLDecoder.decode(linename , “UTF-8”);

For more java knowledge, please pay attention to the java basic tutorial column.

The above is the detailed content of Solution to garbled url in java. 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
Previous article:What is file in java?Next article:What is file in java?