package soapClient;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.soap.*;
//http://stackoverflow.com/questions/15948927/working-soap-client-example
//http://harryjoy.com/2011/10/20/soap-client-in-java/
//http://cafeconleche.org/books/xmljava/chapters/ch03s05.html
//maven http://www.logicsector.com/java/how-to-create-a-wsdl-first-soap-client-in-java-with-cxf-and-maven/
public class SOAPClientSAAJ {
// http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx?wsdl
public static void main(String args[]) throws Exception {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
String url = "http://ws.cdyne.com/emailverify/Emailvernotestemail.asmx";
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(), url);
// print SOAP Response
System.out.println("Response SOAP Message:");
//save response string
File file = new File("soapClient.txt");
FileOutputStream fop = new FileOutputStream(file);
if (!file.exists()) {
file.createNewFile();
}
soapResponse.writeTo(fop);
soapResponse.writeTo(System.out);
soapConnection.close();
}
private static SOAPMessage createSOAPRequest() throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
SOAPPart soapPart = soapMessage.getSOAPPart();
String serverURI = "http://ws.cdyne.com/";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration("example", serverURI);
/*example
Constructed SOAP Request Message:
mutantninja@gmail.com
123
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("VerifyEmail", "example");
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("email", "example");
soapBodyElem1.addTextNode("mutantninja@gmail.com");
SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("LicenseKey", "example");
soapBodyElem2.addTextNode("123");
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", serverURI + "VerifyEmail");
soapMessage.saveChanges();
/* Print the request message */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("getXmlFromSOAPMessage============");
//get request string
System.out.println(getXmlFromSOAPMessage(soapMessage));
return soapMessage;
}
static String getXmlFromSOAPMessage(SOAPMessage msg) throws SOAPException, IOException {
ByteArrayOutputStream byteArrayOS = new ByteArrayOutputStream();
msg.writeTo(byteArrayOS);
return new String(byteArrayOS.toByteArray());
}
}
ref:http://w3school.com.cn/soap/soap_header.asp

沒有留言:
張貼留言