我有一个简单的服务器端代码,它接受请求xml并将其作为字符串插入到Oracle数据库的Clob列中。问题是客户端发送的请求xml使用CP1251编码的文本,但我需要将其插入到使用UTF8编码的Oracle中。现在我为CP1251使用的代码是:
Element soapinElement = (Element) streams.getSoapin().getValue().getAny(); //retrieve request xml
Node node = (Node) soapinElement;
Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
LSOutput output = domImplLS.createLSOutput();
output.setEncoding("CP1251");
Writer stringWriter = new StringWriter();
output.setCharacterStream(stringWriter);
serializer.write(document, output);
String soapinString = stringWriter.toString();此代码可识别以CP1251编码的文本。任务是使用UTF-8编码的可读文本来制作相同的文本。请提出任何建议。
我试过了,但它产生了不可读的字符,而不是西里尔字母:
Element soapinElement = (Element) streams.getSoapin().getValue().getAny();
Node node = (Node) soapinElement;
Document document = node.getOwnerDocument();
DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
LSSerializer serializer = domImplLS.createLSSerializer();
LSOutput output = domImplLS.createLSOutput();
output.setEncoding("CP1251");
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
output.setByteStream(byteArrayOutputStream);
serializer.write(document, output);
byte[] result = byteArrayOutputStream.toByteArray();
InputStream is = new ByteArrayInputStream(result);
Reader reader = new InputStreamReader(is, "CP1251");
OutputStream out = new ByteArrayOutputStream();
Writer writer = new OutputStreamWriter(out, "UTF-8");
char[] buffer = new char[10];
int read;
while ((read = reader.read(buffer)) != -1) {
writer.write(buffer, 0, read);
}
reader.close();
writer.close();
String soapinString = out.toString();发布于 2015-06-26 00:39:11
您可以解码CP1251字符集数据,如下所示
Charset utf8charset = Charset.forName("UTF-8");
Charset cp1251charset = Charset.forName("CP1251");
// decode CP1251
CharBuffer data = cp1251charset.decode(ByteBuffer.wrap(result));并编码为UTF-8字符集
// encode UTF-8
ByteBuffer outputBuffer = utf8charset.encode(data);并将ByteBuffer转换为byte[]
// UTF-8 Value
byte[] outputData = outputBuffer.array();这可能会解决你的问题。
https://stackoverflow.com/questions/31055126
复制相似问题