Question

J'essaie d'accéder à un service Web avec JAX-WS en utilisant:

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

où:

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

Lorsque j'imprime le résultat sur une page utf-8, les caractères utf-8 ne s'affichent pas correctement.

Etant donné que WS fonctionne correctement avec d'autres outils (renvoie UTF-8 fine), j'ai tendance à penser qu'il existe un problème de transformation sourceToXMLString () . Cela pourrait-il détruire mon encodage?

Était-ce utile?

La solution

Essayez ce qui suit:

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; 
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top