如何让java客户端使用参数调用soap WebService方法?

时间:2016-07-25 20:16:24

标签: java web-services soap

如何让java客户端使用参数调用soap WebService方法?

我已经为java客户端尝试了这个类

import javax.xml.soap.*;

public class SOAPClientSAAJ {

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:localhost:8080/myproject/mywebservice?wsdl";
    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 namespace= "http://wsnamespace/";

    // SOAP Envelope
    SOAPEnvelope envelope = soapPart.getEnvelope();
    envelope.addNamespaceDeclaration("example", namespace);

    // SOAP Body
    SOAPBody soapBody = envelope.getBody();
    SOAPElement soapBodyElem = soapBody.addChildElement("Login", "example");
    SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("username", "example");
    SOAPElement soapBodyElem2 = soapBodyElem.addChildElement("password", "example");
    soapBodyElem1.addTextNode("email@example.com");
    soapBodyElem2.addTextNode("1234");

    MimeHeaders headers = soapMessage.getMimeHeaders();
    headers.addHeader("SOAPAction", namespace + "Login");

    soapMessage.saveChanges();

    /* Print the request message */
    System.out.print("Request SOAP Message:");
    soapMessage.writeTo(System.out);
    System.out.println();

    return soapMessage;
}

}

使用这个java webservice方法

@WebMethod(operationName="Login")
public boolean Login(@WebParam(name = "username") String username,
@WebParam(name = "password") String password) {
  System.out.print(username + "-" + password);
}

但用户名和密码始终为null,因此调用该方法时的输出为“null-null”,我想知道如何调用此方法正确发送参数。

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以进行HTTPClient调用并将SOAP请求作为字符串参数传递。 有更好的方法可以在内部执行上述操作,例如使用Apache AXIS2,CXF,JAX-WS等。

我更喜欢通过生成WSDL文件的存根并通过JAVA调用服务来使用CXF。 参考示例: