我正在尝试使用JAX-WS访问Web服务:
Dispatch<Source> sourceDispatch = null;
sourceDispatch = service.createDispatch(portQName, Source.class, Service.Mode.PAYLOAD);
Source result = sourceDispatch.invoke(new StreamSource(new StringReader(req)));
System.out.println(sourceToXMLString(result));
其中:
private static String sourceToXMLString(Source result)
throws TransformerConfigurationException, TransformerException {
String xmlResult = null;
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
OutputStream out = new ByteArrayOutputStream();
StreamResult streamResult = new StreamResult();
streamResult.setOutputStream(out);
transformer.transform(result, streamResult);
xmlResult = streamResult.getOutputStream().toString();
} catch (TransformerException e) {
e.printStackTrace();
}
return xmlResult;
}
当我在utf-8页面上打印结果时,utf-8字符无法正确显示。
由于WS可以与其他工具一起使用(返回UTF-8很好),我倾向于认为我的转换 sourceToXMLString()存在一些问题。这会破坏我的编码吗?
答案 0 :(得分:1)
尝试以下方法:
private static String sourceToXMLString(Source result) throws TransformerConfigurationException, TransformerException {
String xmlResult = null;
try {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
ByteArrayOutputStream out = new ByteArrayOutputStream();
transformer.transform(result, new StreamResult(out));
xmlResult = out.toString("UTF-8");
// or xmlResult = new String(out.toByteArray(), "UTF-8");
} catch (TransformerException e) {
e.printStackTrace();
}
return xmlResult;
}