How to invoke web services on WSDL URL in Java?

2019-02-18 14:34发布

I need to invoke some web service methods within a java web application that I'm building.

E.g each time a user signs up, I want to call the newUser method on a WSDL url via Java. I'd need to pass on some parameters with the request.

Is there any built in Java class, or any publicly available class, which can make this easy, i.e I just supply the URL and the parameters, and it performs the request and returns the response?

If not, what is the standard way of invoking web services on WSDL in Java applications?

1条回答
forever°为你锁心
2楼-- · 2019-02-18 15:13

Run wsimport on the deployed WSDL URL , you can run it from your JDK:

wsimport -p client -keep http://localhost:8080/calculator?wsdl

This step will generates and compile some classes. Notice -keep switch, you need it to keep the generated Java source files.

Calculator.java - Service Endpoint Interface or SEI
CalculatorService - Generated Service, instantiate it

public class MyClientServiceImpl {
    public static void main(String args[]){

    @Override
    public Integer add(int a , int b) {
       CalculatorService service = new CalculatorService();
       Calculator calculatorProxy = service.getCalculatorPort();            
        /**
         * Invoke the remote method
         */
        int result = calculatorProxy.add(10, 20);
        System.out.println("Sum of 10+20 = "+result);
    }
}

If you are using the Java EE 6 supported container then you can use it in this way ,

public class MyClientServiceImpl implements MyClientService {

    @WebServiceRef(wsdlLocation = "http://localhost:8080/calculator?wsdl", 
value = CalculatorService.class)
    private Calculator service;

    @Override
    public Integer add(int a , int b) {
        return service.add(a,b);
    }
}
查看更多
登录 后发表回答