使用不同字符集的 POST 数据
我使用 grails 通过 POST 从一些外部资源接收数据。只要发布数据的字符集是 UTF-8,我的 gail 控制器就可以正常工作。
不幸的是,我也有外部源使用 8859-1 字符集将数据发布到 grails 控制器,结果是 åäö 无法正确处理。
我怎样才能使用 grails 也能够接收不同字符集的 POST 数据,在我的例子中是 utf-8 和 8859-1?
对于发送数据的每个外部源,我有不同的控制器和操作。
谢谢卡罗琳娜
I use grails to receive data by POST from a few external resources. My gails controller works great as long as the character set of the posted data is UTF-8.
Unfortunately I also have external sources posting data to the grails controller using character set of 8859-1 and the result is that the åäö for example cannot be processed correctly.
How can I use grails to also being able to receive POST data of different character sets, in my case utf-8 and 8859-1?
I have different controllers and actions for each external source sending data.
Thanks Karolina
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
也许ISO-8859-1只是无法编码这些字符,而UTF-8中的前256个代码与ISO-8859-1的前256个代码相同(所以如果可以,UTF-8也会成功)
所以问题不是在你的最后,你无法修复它。
Perhaps ISO-8859-1 just cannot encode these characters, and the first 256 codes in UTF-8 are the same as those for ISO-8859-1 (so if it could, UTF-8 would also succeed)
So the problem is not at your end, and you can't fix it.
您无法仅在服务器端可靠地解决此问题,因为当您在 grails 控制器中收到解码后的字符串时,它们已经被 servlet 容器解码,假设字节流采用默认字符集(utf-8)并且 CharsetDecoder 已经替换了无效字节序列与 ?.这意味着您无法可靠地从解码的字符串中获取原始字节以使用其他字符集(iso-8859-1)重新解码它们。
您可以通过在发布时在内容类型标头中指定字符集来在http客户端解决此问题:
另一种选择是发布多部分数据,然后grails应用程序的servlet容器不会将字节解码为字符串,您必须使用任何手动将它们解码为字符串你想要的字符集。
You cant reliably solve this problem solely on server side, because at the time when you received decoded strings in your grails controller, they were already decoded by servlet container assuming byte stream was in default charset(utf-8) and CharsetDecoder already replaced invalid byte sequences with ?. That means you cant reliably get original bytes back from decoded strings to re-decode them using some other charset (iso-8859-1).
You can solve this on http client side by specifying charset in content type header when posting:
Another option is to post mutipart data, then servlet container of grails app wont decode bytes to string and you'll have to manually decode them to string using any charset you want.