How to write java code to invoke a Web-Service?

Step 1 – Get Apache Axis2

Download Apache Axis (http://ws.apache.org/axis2/). Just unzip it in a dir. Lets say your Apache Axis is unzipped here: c:\axis2. Lets call this dir <AXIS_HOME>

Step 2 – Get hold of the wsdl

Get hold of the wsdl file that describes the web-service. Every web-service has an associated wsdl file. Normally, the web-service URL with a ‘?wsdl’ suffix appended to it, will show you the wsdl file. So, if a web-service you want to invoke is available at: http://host:port/superservice/servicemall . You can see the wsdl via a URL: http://host:port/superservice/servicemall?wsdl

Step 3 – Create the Stub

Stub is nothing but the web-service invocation code that you are going to generate now. Go to your command line window, change to dir: <AXIS_HOME>\bin , and run this command:

WSDL2Java -uri servicemall.wsdl

NOTE: servicemall.wsdl should be present in AXIS_HOME\bin dir. Instead of pointing to that file, you could even use a URL format pointing to the wsdl as follows: WSDL2Java -uri http://host:port/superservice/servicemall?wsdl

You will see that stub code has been generated here: <AXIS_HOME>\bin\src. Here you will see that a file ends with *Stub.java name, this is the stub file you need. The contents of this java file look quite complex, but you dont need to worry about all its contents. You will only need to know the Constructor, Parameter, and Response related sub-classes in this file.

Step 4 – Use the Stub

Lets write a MyWebServiceInvoker.java file now, that will invoke the Stub (which in turn invokes the actual web-service). Assuming the name of the name of the stub file generated was: ServiceMallStub, and that the service we want to invoke takes one param (item id), and returns item details when its method getItemDetails is invoked.

You will notice that parameter and the response are also inner classes in the generated stub java file, and they have appropriate methods for your use.

public class MyWebServiceInvoker
{
 public static void main(String[] args)
 {
  try
  {
   com.servicemall.ServiceMallStub serviceMallStub = new com.servicemall.ServiceMallStub();  
   com.servicemall.ServiceMallStub.MyItem theParam = new com.servicemall.ServiceMallStub.MyItem();
   theParam.setItemid("11");
   theParam.MyItemResponse theResp = serviceMallStub.getItemDetails(theParam);
   boolean result = theResp.getItemResult();
   System.out.println("Result is:" + result);   
  }
  catch (Throwable t)
  {
   System.out.println(t);
  }
 }

Step 5 – Run

Just compile and run the MyWebServiceInvoker. To compile, you must put the <AXIS_HOME>\lib\ jar files in the classpath. To run in addition you must have the compiled stub classes in your classpath too. (You could also use the build.xml that is generated along with source code for compilation)

Step 6 – Does it work?

If you dont see any errors, and get a response back from the service, all’s well!

A common cause of exception is HTTP Protocol mismatch (although the exception message doesnt give suitable hint about it!). You may have to ask your stub to use HTTP 1.0 protocol, instead of the default HTTP 1.1 protocol it uses.  This you can do in the constructor class of the stub.

Search for this line: //Set the soap version
_serviceClient.getOptions().setSoapVersionURI(org.apache.axiom.soap.SOAP12Constants.SOAP_ENVELOPE_NAMESPACE_URI);

Now, just below this line, add this line:

_serviceClient.getOptions().setProperty(org.apache.axis2.transport.http.HTTPConstants.HTTP_PROTOCOL_VERSION, org.apache.axis2.transport.http.HTTPConstants.HEADER_PROTOCOL_10);

Compile, and try again.

Tested with: Apache Axis 2.1.3,  JDK 1.5

17 responses

  1. Hi,

    Excellent article. helped me a lot.But I am facing problem in compiling generated and Invoker classes. Can you please tell me in detail how can I compile and run. I am a new-bee in java.

    thanks
    Raju

  2. This is indeed a great explaination and helped me a lot.

    But I am getting some problems in the Invoker Class.

    Where is this response related subclass?
    theParam.MyItemResponse theResp = serviceMallStub.getItemDetails(theParam);

    I am having the problem at this line

    Can’t see any Response class for theParam.

    Please help!
    Many Thanks

    1. Please check the sub-classes inside the main stub class.

  3. Thx a lot.This code really helps me out.People at initial state to web service need this type of document to make steps fast and easier

  4. Hi All,

    I have a project to send files (xml format) from Unix to Web Service-wsdl(Windows).
    Did anybody have such experience ?

    If so, how to do it?
    Is there sample Java code that I can use ?

    Simon Kao
    06.22.2010

  5. This description was reeeeeeeeeeeeeeeeeeealy excellent
    It was short and useful
    thanks a lot!

  6. i need to sample code to call webservice

  7. i have a wsdl,
    i need sample code to call the webservice

    1. Are you using Java?
      If yes, simply download Apache Axis2, and run wsdl2java command…

  8. The way u explained really too gud. Keep posting these type of articles.

    Looking for an article on how to send SOAP attachment to the webservice call..

    Thanks in advance.

    -Kiran

  9. Good that it helped…:)

  10. Hi qnaguru,

    my code is compiling with no errors, but when im trying to run invoker class im getting this error

    log4j:WARN no appenders could be found for logger (org.apache.axis2.description.AxisService
    log4j:WARN Please initialize the log4j system properly. org.apache.axis2.AxisFault: connection reset

  11. Great example, thank you very much!
    You saved me a lot of time.

  12. I am getting below mentioned error, please help me

    java.io.IOException: Non nillable element ‘credentials’ is null.
    at org.apache.axis.encoding.ser.BeanSerializer.serialize(BeanSerializer.java:215)
    at org.apache.axis.encoding.SerializationContext.serializeActual(SerializationContext.java:1504)
    at org.apache.axis.encoding.SerializationContext.serialize(SerializationContext.java:980)
    at org.apache.axis.encoding.SerializationContext.serialize(SerializationContext.java:801)
    at org.apache.axis.message.RPCParam.serialize(RPCParam.java:208)
    at org.apache.axis.message.RPCElement.outputImpl(RPCElement.java:433)
    at org.apache.axis.message.MessageElement.output(MessageElement.java:1208)
    at org.apache.axis.message.SOAPBody.outputImpl(SOAPBody.java:139)
    at org.apache.axis.message.SOAPEnvelope.outputImpl(SOAPEnvelope.java:478)
    at org.apache.axis.message.MessageElement.output(MessageElement.java:1208)
    at org.apache.axis.SOAPPart.writeTo(SOAPPart.java:315)
    at org.apache.axis.SOAPPart.writeTo(SOAPPart.java:269)
    at org.apache.axis.SOAPPart.saveChanges(SOAPPart.java:530)
    at org.apache.axis.attachments.AttachmentsImpl.getAttachmentCount(AttachmentsImpl.java:554)
    at org.apache.axis.Message.getContentType(Message.java:486)
    at org.apache.axis.transport.http.HTTPSender.writeToSocket(HTTPSender.java:343)
    at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:138)
    at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
    at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
    at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
    at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
    at org.apache.axis.client.Call$2.run(Call.java:2832)
    at java.lang.Thread.run(Unknown Source)
    17:19:59,595 ERROR [Thread-0][BeanSerializer] Exception:

  13. Does this code work for java desktop applications or Java Web applications to?
    Thank you.

  14. Francisco andrade | Reply

    Hi there. This was very helpfull… i was invoking a ws through soapUi and it was taking me too much time. This “how to” saved my life! Thanks!

  15. can u pls share the main stub class program & explain bit on the same

Leave a reply to Kiran Cancel reply