我尝试与SOAP服务进行交互。
我能够获得SOAP响应并使用Source sourceContent = soapResponse.getSOAPPart().getContent();
和transformer.transform(sourceContent, result);
,我能够看到输出/响应是什么,并在控制台中显示它。
但是,我需要从响应中提取sessionID
并将sessionID
发送到不同的SOAP请求中。
请建议我提取方法,构建一个新的SOAP请求
解析是我需要做的事情!!
以下是将请求发送到SOAP服务的代码:
public static void main(String args[]) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "https://WWW.DUMMYURL.COM";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// Process the SOAP Response
printSOAPResponse(soapResponse);
soapConnection.close();
}
catch (Exception e) {
System.err.println("Error occurred while sending SOAP Request to Server");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURN = "urn:DUMMYURL.COM";
String serverNS0 = "http://WWW.DUMMYURL.COM";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("urn", serverURN);
envelope.addNamespaceDeclaration("ns0", serverNS0);
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem1 = soapBody.addChildElement("login","urn");
SOAPElement soapBodyElem2 = soapBodyElem1.addChildElement("username","urn");
@SuppressWarnings("unused")
SOAPElement soapBodyElem3 = soapBodyElem2.addTextNode("USERNAME");
SOAPElement soapBodyElem4 = soapBodyElem1.addChildElement("password","urn");
@SuppressWarnings("unused")
SOAPElement soapBodyElem5 = soapBodyElem4.addTextNode("PASSWORD");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", "https://WWW.DUMMYURL.COM" + "login");
soapMessage.saveChanges();
//Print the request message
System.out.print("Request SOAP Message = ");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
private static void printSOAPResponse(SOAPMessage soapResponse) throws Exception {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Source sourceContent = soapResponse.getSOAPPart().getContent();
String source = sourceContent.toString();
System.out.print("\nResponse SOAP Message = ");
// Format it
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
StreamResult result = new StreamResult(System.out);
transformer.transform(sourceContent, result);
System.out.println(transformer.toString());
}
有人可以建议我使用如何保存我在本地获取文件的响应?
目前在上面的代码中,response
将显示在控制台中。
答案 0 :(得分:1)
您可以使用writeTo
界面的SOAPMessage
方法执行相同的操作,例如:
FileOutputStream out = new FileOutputStream("somefile");
soapResponse.writeTo(out);
维诺德。