Friday, January 16, 2015
How to consume a SOAP based web service from java
This post describes how we can access SOAP based web service from java using ksoap2 library. ksoap is a SOAP web service client library for constrained Java environments.First download ksoap2:
https://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2
Then create a java project in Eclipse and add ksoap library to java build path.
Here is the sample code that can be used to access Currency Convertor web service hosted by http://www.webservicex.net
package com.mycode.soap;In line 36 I have set
import java.io.IOException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
public class SoapTest {
public static void main(String[] args) {
try {
final String NAMESPACE = "http://www.webserviceX.NET/";
final String URL = "http://www.webservicex.net/CurrencyConvertor.asmx";
final String SOAP_ACTION = "http://www.webserviceX.NET/ConversionRate";
final String METHOD_NAME = "ConversionRate";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
//set properties
PropertyInfo fromProp = new PropertyInfo();
fromProp.setName("FromCurrency");
fromProp.setValue("USD");
fromProp.setType(String.class);
request.addProperty(fromProp);
PropertyInfo toProp = new PropertyInfo();
toProp.setName("ToCurrency");
toProp.setValue("LKR");
toProp.setType(String.class);
request.addProperty(toProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
String webResponse = response.toString();
System.out.println(webResponse);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
envelope.dotNet = true;For other web services comment that line.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.