我正在编写REST API。我从数据库中获取数据并将其存储在字符串中。然后我将其发送回浏览器,如下所示:
//fetch data from database
String s = ...
// Prepare it for browser
byte[] data = s.getBytes("UTF-8");
// Send it to browser now
out.write(data); // out is an OutputStream received from Jersey through the MessageBodyWriter interface
数据来自具有UTF8编码的PostgreSQL数据库。数据存储在可变字符(5000)中。
当浏览器(Chrome)显示“字符串”时,出现此错误:
error on line 29 at column 285: Input is not proper UTF-8, indicate encoding !
Bytes: 0x19 0x4C 0x29 0x20
在其他浏览器上也会发生相同的问题。
这是发送到浏览器的标题:
200
Content-Type: application/xhtml+xml;charset=UTF-8
总结这是数据流的总结
数据库(UTF8)>休眠>对象> getBytes(“ UTF-8”)>浏览器
我想念什么?
问题出在创建字符串的时候,
String s = ...
As,Java中的String对象没有编码。
唯一具有编码的是byte[]
。因此,如果您需要UTF-8
数据,则需要一个byte []。如果您的String包含意外数据,则问题出在较早的地方,该错误将一些二进制数据错误地转换为String(即,它使用了错误的编码)...因此,与其着重于此s.getBytes()
,不如专注于接收并正确存储字符串。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句