Wednesday, September 5, 2012

Consuming KSOAP web services in Android | Soap Web Services in Android | Web Services in Android


Hello Friends!

I am going to share how to consume soap web services in Android. Important steps are given below-

1)Create new android project name e.g.- KsoapTest
2)Download ksoap2-j2se-full-2.1.2 from ksoap offical website you can use Google for searching.
3)Right click on project and then click on “Build path” then “Configure Build Path”.
4)From Libraries Tab choose “Add Extarnal JARs” then choose your ksoap2-j2se-full-2.1.2 jar file from downloads and click OK.
5)Now Copy – Paste all code in your project and enjoye codeing...

1-Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ksoap.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".Ksoap2TestActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>


2-KsoapTestActivity.java

package ksoap.test;

import java.util.ArrayList;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.TextView;
public class KsoapTestActivity extends Activity {
private final String NAMESPACE = "http://DefaultNamespace/";
private final String URL = "http://10.0.0.17:8080/SecurityAppWebService/services/AppServices?wsdl";
private final String SOAP_ACTION = "http://DefaultNamespace/AppServices";
private final String METHOD_NAME = "getDetails";
ArrayList<Guard> guardList=new ArrayList<Guard>();
// Called when the activity is first created.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo propInfo=new PropertyInfo();
propInfo.type=PropertyInfo.INTEGER_CLASS;
//adding parameters
request.addProperty("a", 10);
request.addProperty("b", 15);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
Log.e("Object response", response.toString());
TextView tv = new TextView(this);
tv.setText("Output: "+response.toString());
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
}

3-main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />

</LinearLayout>

18 comments :

  1. hi im getting following error.. i have added ksoap2-j2se-full-2.1.2 in -> configure build path

    06-20 15:50:17.310: E/dalvikvm(26221): Could not find class 'org.ksoap2.serialization.SoapObject', referenced from method com.example.progressbarwidget.Webservice.getKSOP

    hope you will hepl me

    ReplyDelete
    Replies
    1. I think your jar is not inside your project. please check it should be into libs folder inside your project..
      And if not work try to download another jar from any where else..
      May be some problem in your jar file, for testing extract your jar and check for below classes, which one needed in your project-
      import org.ksoap2.SoapEnvelope;
      import org.ksoap2.serialization.PropertyInfo;
      import org.ksoap2.serialization.SoapObject;
      import org.ksoap2.serialization.SoapSerializationEnvelope;
      import org.ksoap2.transport.HttpTransportSE;

      Thanks,

      Delete
  2. It is working well with the primitive types. But when i try with user defined objects it is not working.
    For ex:
    In WCF I have a Data contract to define Employee, with Int id, String name.
    But when i use it as an argument it gives IOException on androidHttpTransport.call(SOAP_ACTION, envelope);

    I followed the following tutorial.
    http://www.codeproject.com/Articles/29305/Consuming-NET-Web-Services-via-the-kSOAP-library

    Did you already try this kind of application?

    ReplyDelete
    Replies
    1. Please check property.info may be you have put integer... and better place is stackoverflow for any type of doubt an exception...

      Delete
  3. Can you help me ,how to construct this soap req in android,pretty urgent..please help me

    POST http://webservices.someweb.com/V13/Admin/WebserviceAdmin.svc HTTP/1.1
    Accept-Encoding: gzip,deflate
    Content-Type: text/xml;charset=UTF-8
    SOAPAction: "http://tempuri.org/IWebServiceAdmin/VerifyItsAccountHandleAndPasswordGetIdAndProducts"
    Content-Length: 874
    Host: webservices.someweb.com
    Connection: Keep-Alive
    User-Agent: Apache-HttpClient/4.1.1 (java 1.5)\





    ITSME
    ITSMEEE
    23

    ROM
    awesomedude
    dev1


    ReplyDelete
  4. Hi,

    for communication with a SAP webservice i use

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);

    If i examine the communication stream with Wireshark, i can see the correct answer from the ws.
    But on

    SoapObject response = (SoapObject)envelope.getResponse();

    i have an ClassCastException: java.util.Vector
    The answer from the ws is an XML with SOAP Envelope and the data in the body.
    Can you help me please?

    Regards


    ReplyDelete
    Replies
    1. so in which line you are getting error? Just try to print your response in log-cat first after that try to parse..

      Delete
    2. I use your code with little changes:

      SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10); // changed to "VER10"
      envelope.dotNet = false; // changed to false
      envelope.setOutputSoapObject(request);
      HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
      try {
      // new code for basic authorization
      List headerList = new ArrayList();
      headerList.add(new HeaderProperty("Authorization", "Basic " +
      org.kobjects.base64.Base64.encode("username:password".getBytes())));
      androidHttpTransport.call(SOAP_ACTION, envelope, headerList); // List as param added
      // --- to this line there are no exceptions
      SoapObject response = (SoapObject)envelope.getResponse(); // here i getting the ClassCastException

      -> envelope.getRespone is an Vector object. with " Object response = envelope.getResponse(); " is running without exception, but i don't have the methods from SoapObject for parsing the ws response.

      Regards

      Delete
    3. This comment has been removed by the author.

      Delete
    4. I am so sorry dear I have no more idea about xml parsing so please do some google, hope you got anything.

      Delete
  5. Ok, i could fix this with

    java.util.Vector rs = (java.util.Vector) envelope.getResponse();

    but this is an unsafe typecast.
    And i found an other problem. envelope.getResponse do not have the complete XML response from the ws. The original response contains: (i use { and } for the gt and lt signs in XML, because in this comment the tags will ignored:( )

    {env:Envelope xlmns: ...}
    {env:Header}{/}
    {env:Body}
    {n0:ws_name_response}
    {complex_type_name}
    {item}
    {elem1}123{/elem1}
    {elem2}456{/elem2}
    ...
    {/item}{/complex_type_name}
    {complex_type_name2}
    ...
    {/complex_type_name}
    ...
    {/env:Body}

    And the getResponse object contains:

    [
    anyType{
    item=anyType{
    elem1=123;
    elem2=456;
    ...
    };};]

    the problem is, the complex type names are not in this object. Is it possible put this in the object or must i'm looking for another way to requet the informations from the ws?

    Regards

    ReplyDelete
    Replies
    1. Ok this problem is solved ;) envelope.bodyIn cotains the complete XML response.And

      SoapObject responseBody = (SoapObject)envelope.bodyIn;

      do not throw an ClassCastException. And my former problem with this ClassCastException is solved too ;)

      Thank You for the thought-provoking impulses. :)

      Regards

      Delete
    2. ha ha ha :)
      well thanks for post your solution here sure it will help some one..

      Thanks...

      Delete
  6. Hello I need just string response from HelloWorld method which return simple "Hello" string:
    public class Neteesh extends Activity{


    private static final String URL = "http://10.0.2.2:9929/Service1.asmx";
    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String METHOD_NAME = "HelloWorld";
    private static final String SOAP_ACTION = "http://tempuri.org/HelloWorld";

    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i("", "Neteesh Activity Called....");
    TextView textView = new TextView(this);
    setContentView(textView);
    new LongOperation().execute("");
    }


    private class LongOperation extends AsyncTask
    {
    @Override
    protected String doInBackground(String... HelloWorldResult)
    {

    String value = new String();
    System.out.println("Inside getLognoperation method...........");
    PropertyInfo propInfo=new PropertyInfo();
    propInfo.type=PropertyInfo.STRING_CLASS;
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
    request.addProperty("billId", HelloWorldResult[0]);

    SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    soapEnvelope.dotNet=true;
    soapEnvelope.setOutputSoapObject(request);
    AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
    try
    {
    androidHttpTransport.call(SOAP_ACTION, soapEnvelope);
    SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
    value = resultString.toString();
    Log.e("Object response", resultString.toString());
    System.out.println("This getAccountsNames xmls is : "+value);
    } catch (Exception e)
    {
    e.printStackTrace ();
    Log.i(e.getMessage(), "Exception");
    }

    return value;
    }
    }

    }

    ReplyDelete
  7. this code through i can't access .svc web service

    ReplyDelete
    Replies
    1. .svc is no matter here but it should be soap type..

      Delete
  8. This comment has been removed by the author.

    ReplyDelete

Note: Only a member of this blog may post a comment.