Convert StreamResult to string or xml

前端 未结 4 1596
滥情空心
滥情空心 2021-02-02 08:18

Using spring ws to get the StreamResult as below

StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System         


        
相关标签:
4条回答
  • 2021-02-02 08:44

    If you use Spring you could also use this way:

        import org.springframework.core.io.Resource;
        import org.apache.commons.io.IOUtils;
        ....    
        @Value("classpath:/files/dummyresponse.xml")
        private Resource dummyResponseFile;
        ....
        public String getDummyResponse() {
            try {
                if (this.dummyResponse == null)
                    dummyResponse = IOUtils.toString(dummyResponseFile.getInputStream(),StandardCharsets.UTF_8);
            }  catch (IOException e) {
                logger.error("Fehler in Test-Service: {}, {}, {}", e.getMessage(), e.getCause(), e.getStackTrace());
                throw new RuntimeException(e);
            }
            return dummyResponse;
        }
    
    0 讨论(0)
  • 2021-02-02 08:49

    You can get the reader of your StreamSource by using getReader(). You should then be able to use read(char[] cbuf) to write the contents of the stream to a character array which can easily be converted into a string and printed to the console if you wish.

    0 讨论(0)
  • 2021-02-02 08:54

    Try this one:

    try {
        StreamSource source = new StreamSource(new StringReader("<xml>blabla</xml>"));
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        transformer.transform(source,result);
        String strResult = writer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    
    0 讨论(0)
  • 2021-02-02 08:56

    If none of these works, try this

    System.out.println(result.getOutputStream().toString());
    

    Assuming you have this kind of structure ,

    private static StreamResult printSOAPResponse(SOAPMessage soapResponse) throws Exception {
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        Source sourceContent = soapResponse.getSOAPPart().getContent();
        System.out.print("\nResponse SOAP Message = ");
        StreamResult result = new StreamResult(System.out);
        transformer.transform(sourceContent, result);
        return result;
    }
    

    You can try this way , although the same thing, wanted to point it out clearly

    System.out.println(printSOAPResponse(soapResponse).getOutputStream().toString());
    
    0 讨论(0)
提交回复
热议问题