使用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甚至是字符串(只是想看到内容以便生成响应)。
我该怎么做?
答案 0 :(得分:39)
试试这个:
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();
}
答案 1 :(得分:5)
您可以使用getReader()获取StreamSource的读者。然后,您应该能够使用read(char [] cbuf)将流的内容写入字符数组,如果您愿意,可以将其轻松转换为字符串并打印到控制台。
答案 2 :(得分:2)
如果这些都不起作用,请尝试此
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());
答案 3 :(得分:1)
如果您使用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;
}