gpt4 book ai didi

java - JAX-WS 调度响应中的编码错误

转载 作者:行者123 更新时间:2023-12-01 16:11:58 25 4
gpt4 key购买 nike

我正在尝试使用 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() 存在一些问题。这会破坏我的编码吗?

最佳答案

尝试以下操作:

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;
}

关于java - JAX-WS 调度响应中的编码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/820311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com