views:

918

answers:

1

I'm trying to access a web service with JAX-WS using:

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

where:

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

When I print the result on a utf-8 page the utf-8 characters are not displayed correctly.

Since the WS works fine with other tools (returns UTF-8 fine), I tend to think that there is some problem with my transformation sourceToXMLString(). Could this be destroying my encoding?

A: 

Try the following:

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