【问题标题】:Wrong Encoding in JAX-WS Dispatch ResponseJAX-WS 调度响应中的错误编码
【发布时间】:2009-05-04 14:18:50
【问题描述】:

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

【问题讨论】:

    标签: java xml character-encoding jax-ws


    【解决方案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; 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 2019-03-15
      • 1970-01-01
      相关资源
      最近更新 更多