【问题标题】:Convert StreamResult to string or xml将 StreamResult 转换为字符串或 xml
【发布时间】:2014-04-22 12:33:30
【问题描述】:

使用spring ws获取StreamResult如下

StreamSource source = new StreamSource(new StringReader(MESSAGE));
StreamResult result = new StreamResult(System.out);
webServiceTemplate.sendSourceAndReceiveToResult("http://someUri", 
                source, new SoapActionCallback("someCallBack"), result); 
return result;

我得到了结果,但我想将其提取为某种 xml 甚至作为字符串(只想查看内容以生成响应)。

我该怎么做?

【问题讨论】:

标签: java spring-mvc soap spring-ws


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    您可以使用 getReader() 获取 StreamSource 的阅读器。然后,您应该能够使用 read(char[] cbuf) 将流的内容写入字符数组,如果您愿意,可以轻松地将其转换为字符串并打印到控制台。

    【讨论】:

    【解决方案3】:

    如果这些都不起作用,试试这个

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

    假设你有这种结构,

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

    你可以试试这种方式,虽然是一样的东西,还是想指出清楚

    System.out.println(printSOAPResponse(soapResponse).getOutputStream().toString());
    

    【讨论】:

      【解决方案4】:

      如果你使用 Spring,你也可以这样使用:

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

      【讨论】:

        猜你喜欢
        • 2018-08-29
        • 1970-01-01
        • 1970-01-01
        • 2012-10-26
        • 2012-10-10
        • 2013-03-02
        • 1970-01-01
        • 1970-01-01
        • 2016-03-17
        相关资源
        最近更新 更多