Pergunta

Estou tentando acessar um serviço da web com o JAX-WS usando:

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

Onde:

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

Quando imprimir o resultado em uma página UTF-8, os caracteres UTF-8 não são exibidos corretamente.

Como o WS funciona bem com outras ferramentas (retorna UTF-8 Fine), eu tendem a pensar que há algum problema com minha transformação SourcetoxmlString (). Isso poderia estar destruindo minha codificação?

Foi útil?

Solução

Experimente o seguinte:

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; 
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top