Invalid encoding in JAX-WS dispatcher response

I am trying to access a webservice 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 in a utf-8 page, the utf-8 characters are not displayed correctly.

Since WS works great with other tools (returns UTF-8 great), I tend to think that there are some problems with my sourceToXMLString () conversion . Could this destroy my encoding?

0


source to share


1 answer


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

      

+1


source







All Articles