Reputation: 376
I have a simple api made with java spring, which receives texts and saves it in the database. And an application in javascript that formats the texts and sends them to api.
I have texts in several languages (Chinese, Japanese ...) and I was having problems with special characters, so I used encodeURI in javascript to send the text to the api.
When the text is received by the api I need to do the encode saving the original text in the database. But when I have to return the texts to the front application, I need to first encode it again.
Encoded text on the front end, before being sent to api
console.log(text);
//红灯亮起时, 麦克风处于静音状态
text = decodeURIComponent(text);
console.log(text);
//%E7%B4%85%E7%87%88%E4%BA%AE%E8%B5%B7%E6%99%82%2C%20%E9%BA%A5%E5%85%8B%E9%A2%A8%E8%99%95%E6%96%BC%E9%9D%9C%E9%9F%B3%E7%8B%80%E6%85%8B
So I would like to know how to do encodeURI / decodeURI text using java spring.
Upvotes: 3
Views: 7784
Reputation: 12937
You are looking for java.net.URLDecoder
and java.net.URLEncoder
:
String decoded = URLDecoder.decode(s, StandardCharsets.UTF_8);
String encoded = URLEncoder.encode(result, StandardCharsets.UTF_8);
The above approach will work for java 10 and above. For previous versions, you will have to wrap the code in try-catch
block.
Upvotes: 8