任何人都可以帮我开发一个与web服务交互的java程序。
我在netbeans中创建了一个简单的web服务。它会生成wsdl文件,然后从中获取url。
通过使用在netbeans中创建的wsdl文件,我必须在java程序中发送soap请求并获取响应。
我有以下编码,但我不知道如何实现我的要求
import javax.xml.soap.*;
public class SOAPClientSAAJ2 {
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.print("Response SOAP Message:");
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);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:example="http://ws.cdyne.com/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<example:VerifyEmail>
<example:email>mutantninja@gmail.com</example:email>
<example:LicenseKey>123</example:LicenseKey>
</example:VerifyEmail>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// 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.print("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println();
return soapMessage;
}
}
答案 0 :(得分:4)
我建议使用JAX-WS而不是手工制作SOAP消息。使用JAX-WS,您可以生成用于创建SOAP / XML以及发送/接收消息/响应的代码。您剩下要做的就是设置您需要传递的内容的值。在这种情况下,将创建一个VerifyEmail对象,设置其两个属性并调用生成的Web服务客户端的send方法:
ObjectFactory factory = new ObjectFactory;
VerifyEmailRequest request = objectFactory.createVerifyEmailRequest();
VerifyEmail msg = objectFactory.createVerifyEmail();
msg.setEmail("myemail@provider.com");
msg.setLicenseKey("myKey");
request.setVerifyEmail(msg);
VerifyEmailResponse response = myClient.verifyEmail(reques);
这里提到的所有类都将由JAXB为您生成,JAXB使用它。您可以找到更详细的信息here。