Difference in URL decode/encode UTF-8 between Java and JS/AS3 (bug!?)

眉间皱痕 提交于 2019-11-30 22:29:58

escape is a deprecated function and does not correctly encode Unicode characters. Use encodeURI or encodeURIComponent, the latter probably being the method most suitable for your needs.

Javascript is URL encoding your string using Latin-1 charset. Java is URL encoding it using UTF-8.

The URL encoding is really just replacing the characters/bytes that it doesn't recognise. For example, even if you were to stick with ASCII characters, ( would be encoded as %28. You have the additional problem of character sets when you start using non-ASCII characters (any thing longer than 7 bits).

I have been struggling with this problem for hours on end... My problem was a JQuery Ajax call like:

return $.ajax({
        url: '/author!getAuthorContent.action',
        type: 'GET',
        data : {author:name, 'content_type': ct || 'all', 'start': start || 0}
    });

'name' is a String which contains special characters like Jérôme-Serrano

For some reasons the way JS/JQuery was encoding these kind of special characters was incompatible and I couldn't decode it on Java BackEnd...

The solution was:

  • Encode on JS side using var econded = encodeURIComponent(name);
  • Decode them on Java side using String decoded = java.net.URLDecoder.decode(econded ,"UTF-8");

some refetences: http://www.programering.com/a/MjN2ADOwATg.html http://www.theerrormessage.com/2013/10/weird-characters-transmitted-to-and-from-server-through-jquery-ajax-call/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!