Basic KSOAP Android Tutorial


This is a basic KSOAP Android tutorial - here I will show you how to get started with KSOAP on Android. As you may know, we often want to access Web services via hand-held devices, and most likely you will run into trouble parsing the WSDL and the SOAP messages. Since I come from a .NET background, once I started developing on Android, I realized how much work has been Visual Studio doing for me.

That thought took me to search for a framework or library to help me consume Web Services with Android. I ran into KSOAP2, which seemed like a good library, but unfortunately, very badly documented for most scenarios, like passing or returning complex objects, working with arrays of objects or even working with dates.



All of this I needed to find out by myself and this is why I decided to write this tutorial. So, let's begin.

Getting Started with KSOAP on Android


First things first, so you should now go ahead and download the KSOAP library from Sourceforge Google code (*UPDATE* thanks Freddy):
http://code.google.com/p/ksoap2-android/downloads/detail?name=ksoap2-android-assembly-2.4-jar-with-dependencies.jar&can=2&q=


Then copy and paste the KSOAP library in the folder where your Android project will reside. Open Eclipse, start a new Android Project, right-click on the project's name and choose Properties, like this:


The next thing you need to do is to Add the KSOAP .JAR into the Android Project:




Go ahead an press Add JARs... button. Then navigate to the folder where your KSOAP library is and select it. Once you have this done, you are ready to start working with your Web Service library.

Simple Web Service Calls with KSOAP


First, let's take a look at our web service call in Visual Studio:

[WebService(Namespace = "http://vladozver.org/")]
public class SimpleWebServices : System.Web.Services.WebService
{
      [WebMethod]
      public int GetSumOfTwoInts(int Operand1, int Operand2 )
      {
         return Operand1 + Operand2;
      }
}

The service is deployed on my local machine which is on the address: 192.168.1.3. Pay attention on the ending "/" in the Namespace.

Now, KSOAP finally.

KSOAP relies on a basic object called SoapObject. For this SoapObject, there are 3 variables that are important:
The Web Service Namespace
The Web Service Method Name
The Web Service URL

There is another extra variable which is important and is called SOAP_ACTION, but that is basically a concatenation of the Namespace and Method name:

SOAP_ACTION = NAMESPACE + METHOD_NAME;

For now we will create 3 strings for the respective variables:

String NAMESPACE = "http://vladozver.org/";
        String METHOD_NAME = "GetSumOfTwoInts";
        String SOAP_ACTION = "http://vladozver.org/GetSumOfTwoInts";
        String URL = "http://192.168.1.3/VipEvents/Services/BasicServices.asmx";

Then we will create the SoapObject:
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

Parameters in KSOAP are passed via PropertyInfo class instances, so we will create some of those:

PropertyInfo pi = new PropertyInfo();
        pi.setName("Operand1");
        pi.setValue(2);
        pi.setType(int.class);
        Request.addProperty(pi);

        PropertyInfo pi2 = new PropertyInfo();
        pi2.setName("Operand2");
        pi2.setValue(5);
        pi2.setType(int.class);
        Request.addProperty(pi2);

Then we will create another important KSOAP object, and that is Soap Envelope:

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Request);

Because our Web Service is .NET based, we need to set the .dotNet property to true.
Next step is to create a Transport object:

AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);

Lastly, we need to invoke the web service and obtain the result:

try
            {
                androidHttpTransport.call(SOAP_ACTION, envelope);
                SoapObject response = (SoapObject)envelope.getResponse();
                int result =  Integer.parseInt(response.getProperty(0).toString());
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }


That is basically it! I hope you will find this tutorial helpful, as I see that many people are looking for a simple Getting started tutorial on KSOAP Android. For more advanced usage of KSOAP, refer to my other posts on this topic.

131 comments:

Anonymous said...

"First, let's take a look at our web service call:" --> how can I do this?

SeeSharpWriter said...

Because this is a .NET web service, that code is written in Visual Studio. You simply create a new Web Service in Visual studio and you only write WebMethods as you wish.

For more details on how to do that, you can refer to these links:

http://www.youtube.com/watch?v=qOqEKpYbTzw

http://www.asp.net/learn/videos/video-280.aspx

http://msdn.microsoft.com/en-us/library/t745kdsh.aspx

Hope this helps.

mosabua said...

You should look at the ksoap2-android project and use it, since it is actively taking contributions and contains a bunch of fixes like HttpsTransport, more convenience methods on SoapObject and actually working attribute parsing. http://code.google.com/p/ksoap2-android/

SeeSharpWriter said...

Thank you, mosabua, I already contribute to the ksoap2-android project on google code. Thanks for commenting, I appreciate it.

Avinash said...

Hi, i am trying to use this code but i am not able to use PropertInfo parameters
PropertyInfo pi = new PropertyInfo();
pi.setName("Operand1");
pi.setValue(2);
pi.setType(int.class);
Request.addProperty(pi);


Though i have included namespaces,,
can u help me out

SeeSharpWriter said...

Please make sure that you have included all of these:

import org.ksoap2.*;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.Marshal;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

Avinash said...

Hi, i hav imported all the classes of org.Ksoap

but i am getting error in

AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);

because i am not able to find AndroidHttpTransport class in Ksoap that i downloaded from http://sourceforge.net/projects/ksoap2/

SeeSharpWriter said...

Avinash,

if you have this included:
org.ksoap2.transport.AndroidHttpTransport;

then the class should be available - make sure that you have it included.

Also you can check whether you have this line in your Android manifest file:

SeeSharpWriter said...

<uses-permission android:name="android.permission.INTERNET" ></uses-permission>
<uses-sdk android:minSdkVersion="7" />

Avinash said...

Hi,
Thanks for ur reply,but if i include
org.ksoap2.transport.AndroidHttpTransport;

This gives an error,because that library is missing from Ksoap that i downloaded from
http://sourceforge.net/projects/ksoap2/

or is their any latest Ksoap library that i need to download.


Thanks in advance

Avinash said...

Hi ,

thanks for your reply,but if i include
org.ksoap2.transport.AndroidHttpTransport;

this gives an error because i am actually missing this library that i downloaded from

http://sourceforge.net/projects/ksoap2/

i even browsed in the project ,this class is missing .Is their any latest Ksoap download that i need to include?

Thanks in advance

SeeSharpWriter said...

Avinash, please share me your email, I will send it my version of KSOAP to you which contains AndroidHttpTransport for sure - in meanwhile I will check with the code maintainers whether they have made a mistake or not.

frenklin said...

How can I call function with int[] input parameter?

PropertyInfo pi=new PropertyInfo();
pi.setType(int[].class);
pi.setName("aValues");
pi.setValue(aValues);

didn't work

SeeSharpWriter said...

Frenklin, this is probably the only case I don't know exactly how to implement. The situation gets even worse if you wanted to pass an array of complex objects as a parameter.

My best shot here would be to implement the Marshal interface like I did it in this post:

Implementing KSOAP Marshal Interface

This interface basically tells KSOAP how to serialize and deserialize objects.

frenklin said...

Thx, but I don't need serialize complex objects

solved

PropertyInfo pi=new PropertyInfo();
PropertyInfo piElementType=new PropertyInfo(); piElementType.setName("int");
pi.setElementType(piElementType);

Vector v=new Vector();
for(int i=0;i<Ids.length;i++){
v.add(Ids[i]);
}
pi.setName("Ids");
pi.setValue(v);

SeeSharpWriter said...

I understand, excellent! But why do you need the variable piElementType ? By invoking setName() method you only tell the argument name?

Would it work without it?
Like saying:

pi.setElementType(pi);
Vector v = new Vector()
// etc... the rest of the code

frenklin said...

.Net WSDL has array intput parameters looks like
<Ids>
<int>123</int>
<int>123</int>
</Ids>

If you didn't set setElementType ksoap2 generate request
<Ids>
<element>123</element>
<element>123</element>
</Ids>

anil said...

hi, i am beginner to android application.I have created web service in visual studio which looks like:

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' _
_
_
_
Public Class Service
Inherits System.Web.Services.WebService

_
Public Function HelloWorld() As String
Return "Hello Fren how are you"
End Function

End Class


and i have included following coding in my src-com.webservicetest-webservicetest.java as:

package com.webservicetest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;


public class webservicetest extends Activity {
private static final String NAMESPACE = "http://localhost/webservicetest/" ;
private static final String URL = "http://192.168.1.10/webservicetest/Service.asmx";
private static final String HelloWorld_SOAP_ACTION = "http://localhost/webservicetest/HelloWorld";
private static final String METHOD_NAME1 = "HelloWorld";

public static void main(String[] args)
{
GetHelloWorld();
}
/** Called when the activity is first created. */
public static void GetHelloWorld() {

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.dotNet = true;
//envelope.setOutputSoapObject(request);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{

androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());




}
catch(Exception e)
{

e.printStackTrace();

}

}
}

and the problem is that i am not getting any result in android emulator. i am not aware of the error that might have occured..did i miss any coding portion?

please help me out..
Anil

Anil said...

Hi,
i am trying to create web service call in Visual Studio 2008 as:But while running android application i am not getting any output in emulator. can you please tell me whats the problems in my coding so that i can fix it.
_
Public Function HelloWorld() As String
Return "Hello how are you"
End Function

similarly in .java file of android i have used codings as:

package com.webservicetest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;


public class webservicetest extends Activity {
private static final String NAMESPACE = "http://localhost/webservicetest/" ;
private static final String URL = "http://192.168.1.10/webservicetest/Service.asmx";
private static final String HelloWorld_SOAP_ACTION = "http://localhost/webservicetest/HelloWorld";
private static final String METHOD_NAME1 = "HelloWorld";

public static void main(String[] args)
{
GetHelloWorld();
}
/** Called when the activity is first created. */
public static void GetHelloWorld() {

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);
//envelope.dotNet = true;
//envelope.setOutputSoapObject(request);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{

androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());




}
catch(Exception e)
{

e.printStackTrace();

}

}
}


please help me out.

Anil said...

Hi,

i am trying to create web service call in Visual Studio 2008. But while running android application i am not getting any output in emulator. can you please tell me whats the problems in my coding so that i can fix it.

_
Public Function HelloWorld() As String
Return "Hello how are you"
End Function

similarly in .java file of android i have used codings as:


package com.webservicetest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;


public class webservicetest extends Activity {
private static final String NAMESPACE = "http://localhost/webservicetest/" ;
private static final String URL = "http://192.168.1.10/webservicetest/Service.asmx";
private static final String HelloWorld_SOAP_ACTION = "http://localhost/webservicetest/HelloWorld";
private static final String METHOD_NAME1 = "HelloWorld";

public static void main(String[] args)
{
GetHelloWorld();
}
/** Called when the activity is first created. */

public static void GetHelloWorld() {

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);


SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{

androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());




}
catch(Exception e)
{

e.printStackTrace();

}

}
}

i am getting error in "int result = Integer.parseInt(response.getProperty(0).toString());" as "The local variable result is never read". i am not being able to find out as i am new to it. May be my question is not that specific.i hope you will consider it.

Hope to hear soon from you all.
thanking you

Anil said...

Hi,

i am trying to create web service call in Visual Studio 2008. But while running android application i am not getting any output in emulator. can you please tell me whats the problems in my coding so that i can fix it.

_
Public Function HelloWorld() As String

Return "Hello how are you"

End Function

similarly in .java file of android i have used codings as:


package com.webservicetest;

import org.ksoap2.SoapEnvelope;

import org.ksoap2.serialization.SoapObject;

import org.ksoap2.serialization.SoapSerializationEnvelope;

import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;



public class webservicetest extends Activity {

private static final String NAMESPACE = "http://localhost/webservicetest/" ;

private static final String URL = "http://192.168.1.10/webservicetest/Service.asmx";

private static final String HelloWorld_SOAP_ACTION = "http://localhost/webservicetest/HelloWorld";

private static final String METHOD_NAME1 = "HelloWorld";


public static void main(String[] args)

{
GetHelloWorld();

}

/** Called when the activity is first created. */

public static void GetHelloWorld() {


SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);

//SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);



SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.dotNet = true;

envelope.setOutputSoapObject(request);


HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try
{

androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope);

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

int result = Integer.parseInt(response.getProperty(0).toString());





}

catch(Exception e)

{


e.printStackTrace();


}


}

}

i am getting error in "int result = Integer.parseInt(response.getProperty(0).toString());" as "The local variable result is never read". i am not being able to find out as i am new to it. May be my question is not that specific.i hope you will consider it.


Hope to hear soon from you all.

thanking you

Anonymous said...

Very Useful Article..

Sivan said...

i am trying to create web service call in Visual Studio 2008. But while running android application i am not getting any output in emulator. can you please tell me whats the problems in my coding so that i can fix it.

_
Public Function HelloWorld() As String
Return "Hello how are you"
End Function

similarly in .java file of android i have used codings as:


package com.webservicetest;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;


public class webservicetest extends Activity {
private static final String NAMESPACE = "http://localhost/webservicetest/" ;
private static final String URL = "http://192.168.1.10/webservicetest/Service.asmx";
private static final String HelloWorld_SOAP_ACTION = "http://localhost/webservicetest/HelloWorld";
private static final String METHOD_NAME1 = "HelloWorld";

public static void main(String[] args)
{
GetHelloWorld();
}

/** Called when the activity is first created. */

public static void GetHelloWorld() {

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
//SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);


SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);

HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try
{

androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());




}

catch(Exception e)
{


e.printStackTrace();

}

}
}

i am getting error in "int result = Integer.parseInt(response.getProperty(0).toString());" as "The local variable result is never read". i am not being able to find out as i am new to it. May be my question is not that specific.i hope you will consider it.


Hope to hear soon from you all.

Anonymous said...

i am trying to create web service call in Visual Studio 2008. But while running android application i am not getting any output in emulator. can you please tell me whats the problems in my coding so that i can fix it.

_
Public Function HelloWorld() As String

Return "Hello how are you"

End Function

similarly in .java file of android i have used codings as:


package com.webservicetest;

import org.ksoap2.SoapEnvelope;

import org.ksoap2.serialization.SoapObject;

import org.ksoap2.serialization.SoapSerializationEnvelope;

import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;



public class webservicetest extends Activity {

private static final String NAMESPACE = "http://localhost/webservicetest/" ;

private static final String URL = "http://192.168.1.10/webservicetest/Service.asmx";

private static final String HelloWorld_SOAP_ACTION = "http://localhost/webservicetest/HelloWorld";

private static final String METHOD_NAME1 = "HelloWorld";


public static void main(String[] args)

{
GetHelloWorld();

}

/** Called when the activity is first created. */

public static void GetHelloWorld() {


SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);

//SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11);



SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.dotNet = true;

envelope.setOutputSoapObject(request);


HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

try
{

androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope);

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

int result = Integer.parseInt(response.getProperty(0).toString());





}

catch(Exception e)

{


e.printStackTrace();


}


}

}

i am getting error in "int result = Integer.parseInt(response.getProperty(0).toString());" as "The local variable result is never read". i am not being able to find out as i am new to it. May be my question is not that specific.i hope you will consider it.


Hope to hear soon from you all.

SeeSharpWriter said...

@Sivan, your webservice returns string, while you are trying to parse integer

Anonymous said...

So where is the latest ksoap2 library, I'm also having an issue with the following imports:
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;

SeeSharpWriter said...

The latest KSOAP2 library can be downloaded from here: http://sourceforge.net/projects/ksoap2/

After that you need to add the JAR to the project, as denoted in the post.

Anonymous said...

I've already downloaded this KSOAP2 library from http://sourceforge.net/projects/ksoap2/ but it does not contain these classes:
org.ksoap2.transport.AndroidHttpTransport;
org.ksoap2.transport.HttpTransportSE;

SeeSharpWriter said...

Perhaps you could tell me your email address and I will send you my JAR which contains those classes for sure.

I will also ask people who maintain the code to check whether these crucial classes are indeed missing. Thanks

Freddy said...

Your code is working great, however I had a lot of trouble making it work because neither version in http://sourceforge.net/projects/ksoap2/ works with it, for all of those interested you should use this one:

ksoap2-android-assembly-2.4-jar-with-dependencies.jar

You can fin it in: http://code.google.com/p/ksoap2-android/downloads/detail?name=ksoap2-android-assembly-2.4-jar-with-dependencies.jar&can=2&q=

It's actually KSOAP2-android not just KSOAP2.

Also you have a mistake in the try catch clausule where you use the AndroidHttpTransport, which should be like this:

try
{
AndroidHttpTransport transp = new AndroidHttpTransport(URL);
transp.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
btn.setText(result.toString());

}
catch(Exception e)
{ btn.setText(e.toString());
e.printStackTrace();
}

For everyone who wants it, this is the full code that I've tested and it's working 100% fine using Eclipse Helios Release Build id: 20100617-1415


package com.android.KSOAP;
import org.ksoap2.*;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.Marshal;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import org.ksoap2.transport.AndroidHttpTransport;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class KSOAP extends Activity implements View.OnClickListener
{
Button btn;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = new Button(this);
btn.setOnClickListener(this);
setContentView(btn);

}
@Override
public void onClick(View view)
{
String NAMESPACE = "http://vladozver.org/";
String METHOD_NAME = "GetSumOfTwoInts";
String SOAP_ACTION = "http://vladozver.org/GetSumOfTwoInts";
String URL = "http://192.168.1.4/SimpleWebService/SimpleWebService.asmx";
SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("Operand1");
pi.setValue(2);
pi.setType(int.class);
Request.addProperty(pi);

PropertyInfo pi2 = new PropertyInfo();
pi2.setName("Operand2");
pi2.setValue(5);
pi2.setType(int.class);
Request.addProperty(pi2);


SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
try
{
AndroidHttpTransport transp = new AndroidHttpTransport(URL);
transp.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
btn.setText(result.toString());

}
catch(Exception e)
{ btn.setText(e.toString());
e.printStackTrace();
}

}
}

It just show the result of the call to the webservice in the button caption.

Best Regards

Freddy Ayala

Anonymous said...

Thanks a lot... very helpful link... one more que, what if i want to send file?

SeeSharpWriter said...

You would need to convert it to array of bytes and then send it to the server. I had a pretty rough time sending an image via web service. I will paste the code if I find it.

Raghav Rajagopalan said...

hi,

Can Some one help me in using webservice in android.

I have a Login screen. When user enters input in Login and password columns on click login Validation if user has entered is valid move to next screen and display error when wrong username and password.

Any help I will be very much thankful

Regards,
Raghav Rajagopalan

Fizch said...

Thanks!!! This post was very insightful and helped me to get my Android app connected to my .Net web service.

Anonymous said...

Thanks for the great info!

thak said...

I'm having a heck of a time getting any sort of response from the SOAP service format that I've attached. Is it because the parameters are nested "two deep"?

I've tried setting up an "AuthenticationInfo" class with "userName" and "password", but it fails with a "NullPointerException" error when doing the basic "httpTransportSE.call(SOAP_ACTION, envelope)" statement.

It seems like based on everything I've read that I need a "LogIn" class that contains the "AuthenticationInfo" class, which seems ridiculous. Please tell me I'm crazy, and that there's an easy way to do this.

(I've replaced the <> with [].)

[soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://sample.com" xmlns:types="http://sample.com/encodedTypes" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"]
[soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"]
[tns:LogIn]
[oAuthenticationInfo href="#id1" /]
[/tns:LogIn]
[tns:AuthenticationInfo id="id1" xsi:type="tns:AuthenticationInfo"]
[userName xsi:type="xsd:string"]string[/userName]
[password xsi:type="xsd:string"]string[/password]
[/tns:AuthenticationInfo]
[/soap:Body]
[/soap:Envelope]

SeeSharpWriter said...

Thak, take it easy a little bit :)
As per my understanding, you need to implement a Login functionality via SOAP Webservice.. Right ?

Please paste your whole code from Android's side for invoking the service, and the Webservice signature from .NET's side.

Anonymous said...

Hi,

I couldn't use PropertyInfo methods, ie setName, setValue, setType. I got error for SoapObject.AddProperty as well. Please help.

I added the KSOAP library to the project and I imported all that you have given

//import org.ksoap2.*;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.Marshal;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;//

thak said...

Unfortunately, I can't make changes to the .NET service at all, I can only consume it. And I can't post all of my code online either due to NDA.

I was hoping that the service definition I posted from the asmx would be enough to identify how deeply I need the object to be nested.

Please let me know how I can contact you directly if it's not too much trouble.

Thanks. :)

SeeSharpWriter said...

@Anonymous,
please try to download and use KSOAP from here: http://code.google.com/p/ksoap2-android/downloads/detail?name=ksoap2-android-assembly-2.4-jar-with-dependencies.jar&can=2&q=




@thak, since you cannot paste any code,
basically you need to have exact replica of the classes from both Android and .NET side, and read this post to see how to pass and retrieve complex objects between web services and Android:
http://seesharpgears.blogspot.com/2010/10/ksoap-android-web-service-tutorial-with.html

Anonymous said...

@ SeeSharpWriter

Thanks. After I used the KSOAP you gave, it works.

But I couldnt connect to webservice. My program runs before the below line.

androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();

I tried setting the text view.
textview4.setText("Inside TRY" );

It was successful just before the "androidHttpTransport.call", but nothing happens after that. Please help.

SeeSharpWriter said...

Please paste the whole code for invoking the web service and the .NET web service signature.

thak said...

The WSDL for my "nested object" is:

[s:complexType name="AuthenticationInfo"]
[s:sequence]
[s:element minOccurs="0" maxOccurs="1" form="unqualified" name="userName" type="s:string" /]
[s:element minOccurs="0" maxOccurs="1" form="unqualified" name="password" type="s:string" /]
[/s:sequence]
[/s:complexType]

Here's the code on the Android side (obviously, I've got a class for AuthenticationInfo with two string variables):


AuthenticationInfo auth = new AuthenticationInfo("username", "password");

SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

PropertyInfo pi = new PropertyInfo();
pi.setName("AuthenticationInfo");
pi.setValue(auth);
pi.setType(auth.getClass());
Request.addProperty(pi);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.bodyOut = Request;
envelope.encodingStyle = SoapSerializationEnvelope.ENC;
envelope.setOutputSoapObject(Request);

envelope.addMapping(NAMESPACE, "AuthenticationInfo", new AuthenticationInfo().getClass());

HttpTransportSE httpTransportSE = new HttpTransportSE(URL);
httpTransportSE.debug = true;

try
{
httpTransportSE.call(SOAP_ACTION, envelope);

Object response = envelope.getResponse();
SoapObject body = (SoapObject) envelope.bodyIn;

SoapPrimitive resultString = (SoapPrimitive) envelope.getResponse();
TextView tv = (TextView)findViewById(R.id.tvResult);
tv.setText(resultString);
}
catch(IOException e) {
System.out.println(e.toString());
e.printStackTrace();
}
catch(XmlPullParserException e) {
System.out.println(e.toString());
e.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
}

SeeSharpWriter said...

Your AuthenticationInfo on Android side class needs to implement the KVMSerializable interface.. please see this post of mine:

http://seesharpgears.blogspot.com/2010/10/ksoap-android-web-service-tutorial-with.html

There I describe how a class should implement the interface.

thak said...

I did the KVMSerializable bit already, but I missed the "getPropertyInfo" function, so thanks for mentioning that.

It looks like the problem is in the actual envelope formatting. Here's what it's expecting (captured from an existing .NET Windows app):

[?xml version="1.0" encoding="utf-16"?]
[soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://sample.com" xmlns:types="http://sample.com/encodedTypes" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"]
[soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"]
[tns:LogIn]
[oAuthenticationInfo href="#id1" /]
[/tns:LogIn]
[tns:AuthenticationInfo id="id1" xsi:type="tns:AuthenticationInfo"]
[userName xsi:type="xsd:string"]userid[/userName]
[password xsi:type="xsd:string"]password[/password]
[/tns:AuthenticationInfo]
[/soap:Body]
[/soap:Envelope]

And here's what I'm sending from ksoap2:


[v:Envelope xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns:d="http://www.w3.org/2001/XMLSchema" xmlns:c="http://schemas.xmlsoap.org/soap/encoding/" xmlns:v="http://schemas.xmlsoap.org/soap/envelope/"][v:Header /][v:Body][LogIn xmlns="http://sample.com/" id="o0" c:root="1"][AuthenticationInfo i:type="n0:AuthenticationInfo" xmlns:n0="http://sample.com/"][userName i:type="d:string"]userid[/userName][password i:type="d:string"]password[/password][/AuthenticationInfo][/LogIn][/v:Body][/v:Envelope]

thak said...

The more I'm looking at this, the more it looks like it may be the ksoap2 library switching around the 1.1 and 1.2 specifications. Or perhaps it's the service I'm trying to use that's doing that. My head hurts. :)

Anonymous said...

Hi,

Can the simulator access the internet through the PC to connect to the webservice.

Because I can access the webservice( which is in same network as host PC) through the host PC browser, But if I run the emulator nothing happens.

Please help. Thanks a ton :)

SeeSharpWriter said...

You need to have the following permission in the manifest file:

<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
</manifest>

Munna said...

Hi, I'm a newbie to android and java.. I have two webservices, one will insert the values into database, and the other will return the values from the database.

My first webservice is working fine, I'm able to insert the values into databse..

And my second webservice is also working fine, but I'm returning the values as a dataset..

So I'm getting "java.lang.ClassCastException: org.ksoap2.serialization.SoapObject"

Can anyone help me how to solve getting or parsing the resultant dataset values..

Thanks in advance

SeeSharpWriter said...

I suggest that you return an array of your objects instead of DataSet - also remember to write the same class on both Android and .NET side.

!ok$ said...

Hi , how can i make an session between two call ...

Anonymous said...

i am getting this error

java.net.Connect Exception:localhost127.0.0.1:80 Connection refused

Anonymous said...

Thanks above code works good.

Anonymous said...

Hi everyone,I'm writing a soap client using ksoap.My problem is that I receive an empty response,this is my code:

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.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class SOAP2 extends Activity {



private static String SOAP_ACTION = "http://session/getAllPositions";
private static String METHOD_NAME = "getAllPositions";
private static String NAMESPACE = "http://session/";
private static String URL ="http://192.41.218.56:8080/WSGeoEAR-WSGeoServer/NavFinderBean?WSDL";

TextView tv;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
// tv=(TextView)findViewById(R.id.result);
try {

Log.i("Invio request","1");
//Chiamo il Metodo del WebServer
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

Log.i("PROPERTYINFO","2");
/* PropertyInfo propertyInfo=new PropertyInfo();
propertyInfo.setName("arg0");
propertyInfo.setValue(1);
//propertyInfo.setNamespace(NAMESPACE);

request.addProperty(propertyInfo);*/
request.addProperty("arg0", 1);
Log.i("Aggiunte le proprietà alla request","3");

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

envelope.dotNet = true;
envelope.setOutputSoapObject(request);
Log.i("ENVELOPE SETTATA","4");
envelope.setAddAdornments(false);
//envelope.headerOut = null;

HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
Log.i("Trasport url","5");
androidHttpTransport.debug = true;
androidHttpTransport.call(SOAP_ACTION, envelope);
Log.i("Envelope inviata","6");
//Prende la risposta SOAP e ne estrae il corpo

SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;

Log.i("Ricevuta risposta","7");
Log.i("PropertyCount","" + resultsRequestSOAP.getPropertyCount());
Log.i("Contiamo gli attributi","" +resultsRequestSOAP.getAttributeCount());

String res = resultsRequestSOAP.toString();
Log.i("Metto la risposta nella var res","8");

((TextView)findViewById(R.id.lblStatus)).setText(res);


Log.i("STAMPO A VIDEO","9");
}catch(Exception E) {
((TextView)findViewById(R.id.lblStatus)).setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
Log.i("Stampo errore","9");
}
}
}

Can you help me?

SeeSharpWriter said...

Could you paste the signature of the Web Service you are trying to reach? The URL does not seem like a .NET web service to me

Anonymous said...

I've only the WSDL,it isn't a .net web service,but a SOAP web service.

Dan Steg said...

Anyway to see the actual xml produced and recieved?

I'm trying to connect to a webservice to I don't control, so I know very little about it, just the calls. Normally I'd just make some kinda wsdl binding, however, that's not poissible in android :S

Seeing the actual xml would really help alot with the debugging

thanks

Anonymous said...

I've your same problem Dan Steg,I've tried to configure tcp/ip monitor on eclipse,but it doesn't work for me..

SeeSharpWriter said...

If it is not a .NET web service, this code will not work for you.

SeeSharpWriter said...

Dan, I think there is a debug mode in KSOAP2, but I have never used it, so you might consider searching through the documentation.
Anyways, even though you do not control the web service, you can judge what input/output parameters are.

Dan Steg said...

Thanks SeeSharpWriter

I'll look into that. what the other guy said about tcp/ip also gave me an idea. Running the app is on the emulator, so checking eclipse's tcp/ip wont help none, however, mayber you can look a bit closer on the androidHttpTransport, that's the instance making all the calls.

Dan Steg said...

AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);
androidHttpTransport.debug = true;

then make the call: androidHttpTransport.call...etc

after the call:
Log.d("rq.dump", androidHttpTransport.requestDump);
Log.d("rq.dump", androidHttpTransport.responseDump);

Then you can mark the line in the eclipe log and press ctrl+c and paste it in a notepad etc.

and there, you have the request + responce.

DoM said...
This comment has been removed by the author.
DoM said...

Thanks for your answer,they helped me.Now I'm trying to post the logcat response,but it doesn't view when I want to send the comment.I think the tags are the problems..How can I post it?

Conrad Yoder said...

SeeSharpGears, thanks much for your tutorial here - it is helping me get started on a current project. I have a few questions here:

- I am using ksoap2-android-assembly version 2.5.4 and it appears that AndroidHttpTransport has been deprecated in favor of HttpTransportSE. Are there any known issues in using the latter in favor of the former?

- My SOAP endpoint is not from .NET, but from SQL Server (2005) Native XML Web Services. Is there anything else, besides changing envelope.dotNet = true to false, that needs to be changed? (I still have to deal with authentication, I know - I am working on that as well)

- Any knows issues with using https on the SOAP endpoint instead of http?

Thanks again for all your responses here!

SeeSharpWriter said...

Hi Conrad,

I haven't noticed any issues by using HttpTransportSE (yet) :D

Yes, setting the envelope.dotNet is the only setting you need to take care of for using .NET services.
Whoa, I have never used it against SQL Server native web services. If you have time, please share with us how are you doing that.

Oh and about the HTTPS, I am afraid many people have experienced problems using it :S , but who knows, maybe you will be lucky.

Hope I helped.

Conrad Yoder said...

SSW, Thanks for the response.

I don't know if this will help in you interpreting what I need to do here, but below is an example of the WS-Security header for a SQL SOAP connection from http://msdn.microsoft.com/en-us/library/ms180919%28v=SQL.90%29.aspx:

========================================
[SOAP-ENV:Header]
[wsse:Security xmlns:wsse=
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"]
[wsse:UsernameToken]
[wsse:Username]JohnDoe[/wsse:Username]
[wsse:Password Type=
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"]pass-word1[/wsse:Password]
[/wsse:UsernameToken]
[/wsse:Security]
[/SOAP-ENV:Header]
========================================


and here is how the invocation query should be formed from http://msdn.microsoft.com/en-us/library/ms345123%28v=sql.90%29.aspx#:
========================================
[SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"]
[SOAP-ENV:Body]
[hello_world xmlns="http://tempuri.org/"]
[msg]Hello World![/msg]
[/hello_world]
[/SOAP-ENV:Body]
[/SOAP-ENV:Envelope]
========================================

I'm beginning to wonder, given the complexity of KSOAP2, and the limited number of bytes I am going to be dealing with, might it just be easier to use some sort of raw HTTP interface? Or am I asking for even more trouble by doing it that way?

Conrad Yoder said...

SSW, Thanks for the response.

I don't know if this will help in you interpreting what I need to do here, but below is an example of the WS-Security header for a SQL SOAP connection from http://msdn.microsoft.com/en-us/library/ms180919%28v=SQL.90%29.aspx:

========================================
[SOAP-ENV:Header]
[wsse:Security xmlns:wsse=
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"]
[wsse:UsernameToken]
[wsse:Username]JohnDoe[/wsse:Username]
[wsse:Password Type=
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText"]pass-word1[/wsse:Password]
[/wsse:UsernameToken]
[/wsse:Security]
[/SOAP-ENV:Header]
========================================


and here is how the invocation query should be formed from http://msdn.microsoft.com/en-us/library/ms345123%28v=sql.90%29.aspx#:
========================================
[SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"]
[SOAP-ENV:Body]
[hello_world xmlns="http://tempuri.org/"]
[msg]Hello World![/msg]
[/hello_world]
[/SOAP-ENV:Body]
[/SOAP-ENV:Envelope]
========================================

I'm beginning to wonder, given the complexity of KSOAP2, and the limited number of bytes I am going to be dealing with, might it just be easier to use some sort of raw HTTP interface? Or am I asking for even more trouble by doing it that way?

Conrad Yoder said...

SSW, thanks for the comments. When I make the call to HttpTransportSE.call(), I am getting a RuntimeException in the debugger. Does this sound like a familiar problem, or do I need to post my code to see what's happening?

Conrad Yoder said...

I don't know if this will help in you interpreting what I need to do here, but at this webpage is an example of the WS-Security header for a SQL SOAP connection from http://msdn.microsoft.com/en-us/library/ms180919%28v=SQL.90%29.aspx (I tried to post the specific code, but my post does not appear on the page then.)

And here is how the invocation query should be formed: http://msdn.microsoft.com/en-us/library/ms345123%28v=sql.90%29.aspx#

I'm beginning to wonder, given the complexity of KSOAP2, and the limited number of bytes I am going to be dealing with, might it just be easier to use some sort of raw HTTP interface? Or am I asking for even more trouble by doing it that way?

SeeSharpWriter said...

There is probably an error in your application. You should check whether your Android app has access to the Internet in the config file, and make sure the NAMESPACE, SOAP_ACTION and URL are correct.
My opinion is that using native web services from SQL Server will cause you a lot of headache.

Conrad Yoder said...

I do have
[uses-permission android:name="android.permission.INTERNET" /]
in my AndroidManifest.xml file (I am able to connect to a web server in another part of my code).

Here are the relevant variables:
String NAMESPACE = "http://tempuri.org/";
String SOAP_ACTION = "http://tempuri.org/GetPageNumber";
String URL = "http://10.199.5.30:88/ou812";

Anonymous said...

Hello Everyone, I have developed my app that uses a web Service i also developed. Using the Emulator i can connect to the web service and get response from it, but when i installed the app into an android phone i can not get any response. What is the problem?

SeeSharpWriter said...

Do you have the permission for internet usage in your Android config file?

[uses-permission android:name="android.permission.INTERNET" ][/uses-permission]

Replace [ with < and ] with >.

Anonymous said...

Thanks for this post!!
You save me a lot of time in debugging my code!

SeeSharpWriter said...

I'm glad I helped! :)

Anonymous said...

I looked for this jar quiet a bit. This blog really helped..

bharath2598 said...

hi sir

please help me how to send xml file to server

SeeSharpWriter said...

Hi, bharath2598, just transfer the file as a string and convert it to XML file on the server.

bharath2598 said...

Hi sir

I want to send xml file object to sever.Is there any possibility to create object for xml and send it to server

SeeSharpWriter said...

I don't know, to be honest. Maybe anyone reading the comments can add up to your question.

christus valerian said...

HOW TO SEND VALUES TO THE WEBSERVICE FROM ANDROID

Public Class Service1 Inherits System.Web.Services.WebService Public Class InfoRequest

Private NameField As String
Private num1field As Integer
Private num2field As Integer
'''
Public Property Name() As String
Get
Return Me.NameField
End Get
Set(ByVal value As String)
Me.NameField = value
End Set
End Property
'''
Public Property num1() As Integer
Get
Return Me.num1field
End Get
Set(ByVal value As Integer)
Me.num1field = value
End Set
End Property
'''
Public Property num2() As Integer
Get
Return Me.num2field
End Get
Set(ByVal value As Integer)
Me.num2field = value
End Set
End Property

End Class
Public Class InfoResponse

Private totalField As Integer

'''
Public Property total() As Integer
Get
Return Me.totalField
End Get
Set(ByVal value As Integer)
Me.totalField = value
End Set
End Property

End Class
_
Public Function total(ByVal validationRequest As InfoRequest) As InfoResponse
Dim resp As New InfoResponse
Dim req = validationRequest

Dim name As String = req.Name
Dim num1 As Integer = req.num1
Dim num2 As Integer = req.num2
Dim tot As Integer = num1 + num2
resp.total = tot
Return resp
End Function

End Class

Prasildas said...

Hi,
How to return a data table of a web service to list view in android.

SeeSharpWriter said...

Prasildas, do not return a data table from the web service. Instead, create a custom class and then return an array of your custom objects back to Android.

Nath of God said...

My web service never receives the parameters... I cant understand why !!

NMO said...

Hi! I'm trying to pass an enum class to my WS.
When it receives the call, the enum parameter is null.
Here's the code

This class is the WS main parameter thats owns the enum

public class MyObject implements KvmSerializable{
...
private MyEnum myEnum;
...

@Override
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) {
switch (arg0){
case 0:
arg2.type = MyEnum.class;
arg2.name = "myEnum";
break;
case1:
...
}
}

This is the enum Class

public enum MyEnum implements KvmSerializable {

VALUE1,
VALUE2,
VALUE3,
VALUE4;

public String value() {
return name();
}

public static MyEnum fromValue(String v) {
return valueOf(v);
}

@Override
public Object getProperty(int arg0) {
// TODO Auto-generated method stub
return value();
}

@Override
public int getPropertyCount() {
// TODO Auto-generated method stub
return 1;
}

@Override
public void getPropertyInfo(int arg0, Hashtable arg1, PropertyInfo arg2) {
arg2.type = PropertyInfo.STRING_CLASS;
arg2.name = "value";
}

@Override
public void setProperty(int arg0, Object arg1) {

}
}

I'm not very comfortable with this code because I don't really like the getPropertyInfo on the enum.
Any help? Is there anyway to pass an enum as a parameter or I shouldn't be using enums here at all?

VenkataKrishna said...
This comment has been removed by the author.
VenkataKrishna said...

Hi I am calling .net web service from Android Application .I am getting 'v' instead of 'soap' in the web request.
This is my code:

Map parameterMap=new HashMap();
parameterMap.put("EmailAddress", "venkata.vanaparthi@dharani.co.in");
parameterMap.put("Password", "12345678");
parameterMap.put("TokenID", "071D394A29E37AE4B14401B0EA9EB39F793A81E8");
.........................
AndroidHttpTransport aht = null;
SoapSerializationEnvelope sse = null;
aht = new AndroidHttpTransport("http://parking.dharani.org/Services.asmx");
sse = new SoapSerializationEnvelope(SoapEnvelope.VER11);
sse.encodingStyle = SoapSerializationEnvelope.ENC2003;
sse.dotNet = true;
sse.setAddAdornments(false);
sse.setOutputSoapObject(requestSoapBody("AddCar", parameterMap));
aht.setXmlVersionTag("");
aht.debug=true;
aht.call("http://parkinghero.com/"+ "AddCar", sse);
SoapObject resultsRequestSOAP = (SoapObject) sse.bodyIn;

private SoapObject requestSoapBody(String methodName,
Map propMap) {
SoapObject request = new SoapObject("http://parkinghero.com/",
methodName);
if (propMap != null) {
int mapsize = propMap.size();
Iterator keyValuePairs1 = propMap.entrySet().iterator();
for (int i = 0; i < mapsize; i++) {
Map.Entry entry = (Map.Entry) keyValuePairs1.next();

final String key = (String) entry.getKey();
final String value = (String) entry.getValue();
request.addProperty(key, value);
}

}
return request;
}

abhi999 said...
This comment has been removed by the author.
abhi999 said...

Can anyone tell me how to consume a WCF web service through KSOAP2 from android? Please explain with example.

SeeSharpWriter said...

I do not have a working example, but someone here said that it was the same as if the service was ASMX, as far as I remember.

If anyone has a working example, please share it with the others.

Anonymous said...

Can anyone please let me know what changes I need to make in order to make this to work in java and not dotnet ? Thanks.

Brandon Edley said...

thanks for the information you have provided here for us. When i send the information off i get a response of -1 anytype. Invalid api id and key. (ive double and triple checked so i know they are correct. I have to send an api key and an ID to get a response. This is what i have so far.
package com.example;

public class Test implements KvmSerializable
{ public String ApiID;
public String ApiKey;
public Test(){}
public Test(String apiID, String apiKey) {
ApiID = apiID;
ApiKey = apiKey;
}
public Object getProperty(int arg0) {

switch(arg0)
{

case 0:
return ApiID;
case 1:
return ApiKey;
}

return null;
}

public int getPropertyCount() {
return 2;
}

public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index)
{
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "ApiID";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "ApiKey";
break;
default:break;
}
}

public void setProperty(int index, Object value) {
switch(index)
{

case 0:
ApiID = value.toString();
break;
case 1:
ApiKey = value.toString();
break;
default:
break;
}
}
}

Brandon Edley said...

This is the class doing the consuming

package com.example

public class AndroidClientService extends Activity {


private static final String SOAP_ACTION = "https://book.mylimobiz.com/api/Test";

private static final String API_ID = "r0rnyW1KLbxZE0Z";

private static final String API_KEY = "Q0TUfJ$G6r9GP5OMwHCU";

private static final String OPERATION_NAME = "Test";


private static final String WSDL_TARGET_NAMESPACE = "https://book.mylimobiz.com/api";


private static final String SOAP_ADDRESS = "https://book.mylimobiz.com/api/ApiService.asmx";


@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);


TextView textView = new TextView(this);


setContentView(textView);

Test T = new Test(API_ID, API_KEY);

SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,

OPERATION_NAME);


PropertyInfo pi = new PropertyInfo();
pi.setName("Test");
pi.setNamespace(WSDL_TARGET_NAMESPACE);
pi.setValue(T);

pi.setType(T.getClass());
request.addProperty(pi);


SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(

SoapEnvelope.VER11);
envelope.implicitTypes = true;
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
envelope.addMapping(WSDL_TARGET_NAMESPACE, "Test", new Test().getClass());



HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
httpTransport.debug = true;
httpTransport.setXmlVersionTag("");

try

{

httpTransport.call(SOAP_ACTION, envelope);


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

T.ApiID = response.getProperty(0).toString();
T.ApiKey = response.getProperty(1).toString();

textView.setText(response.toString());


/*Object response = envelope.getResponse();

textView.setText(response.toString()); */

} catch (Exception exception)

{

textView.setText(exception.toString());

}

}
}
the link for the soap sample request and response https://book.mylimobiz.com/api/ApiService.asmx?op=Test.

Brandon Edley said...

Is there any info that you may need to be able to kindly assist me with this issue. Its driving me nuts.

SeeSharpWriter said...

What is the issue you are facing?

Brandon Edley said...

Hey man. Its in the above post. I actually have the last 3 post. I had to make three because of the text count. In the end. i cant get the server to accept the api id and key. Thanks for your reply btw.

Brandon Edley said...

I still havent figured this out. Started another project working with JSON and its much simpler. Whenever yuu get the time I would love to know what Im actually doing wrong. All of my code is in the above posts.

Tunandroid said...

Hi,
SeeSharpWriter can you send me the ksoap jar file that contains org.ksoap2.transport.androidhttptransport
on Darkairouanside@gmail.com ?

SeeSharpWriter said...

Have you tried downloading KSOAP 2 from here?

http://code.google.com/p/ksoap2-android/downloads/detail?name=ksoap2-android-assembly-2.4-jar-with-dependencies.jar&can=2&q=

Anonymous said...

Thanks your code works good.
If i have to send arry of byte to web service
http://192.168.7.158/uploader/FileUploader.asmx/UploadFile?f=BYTEaRRY&FileName=mypic.PNG

POST /uploader/FileUploader.asmx HTTP/1.1
Host: 192.168.7.158
Content-Type: text/xml; charset=utf-8
Content-Length: length
SOAPAction: "http://tempuri.org/UploadFile"





base64Binary
string

SeeSharpWriter said...

Basically I have done this with encoding the byte array and then sending it to the server. When it arrives to the server you should decode it and assemble the picture.

If I find the code I will post it here.

vivek shah said...

What is full form of ksoap???

Anonymous said...

nice post..I have one silly problem though,I can't seem to understand the difference between the namespace and url.I know it's silly but can u help me ?,thank you in advance..

Anonymous said...

When i tried to create the trasport object my eclipse compiler marked it as depreacated.What shoud i do now? ignore it or is there another similar object?

Daniel Chivescu said...

Since ksoap2, AndroidHttpTransport is deprecated and you now have to use HttpTransportSE for the same purpose.

Anonymous said...

Mr SeeSharpWriter i download the ksoap from the link you give and put it well in my project but i have these errors :
07-10 03:09:11.631: E/dalvikvm(30382): Could not find class 'org.ksoap2.serialization.SoapObject', referenced from method st.jon.testKso.onCreate
07-10 03:09:11.631: W/dalvikvm(30382): VFY: unable to resolve new-instance 63 (Lorg/ksoap2/serialization/SoapObject;) in Lst/jon/testKso;
07-10 03:09:11.641: D/dalvikvm(30382): VFY: replacing opcode 0x22 at 0x0004
07-10 03:09:11.671: I/dalvikvm(30382): Could not find method org.ksoap2.serialization.PropertyInfo.setName, referenced from method st.jon.testKso.onCreate
07-10 03:09:11.671: W/dalvikvm(30382): VFY: unable to resolve virtual method 65: Lorg/ksoap2/serialization/PropertyInfo;.setName (Ljava/lang/String;)V
07-10 03:09:11.671: D/dalvikvm(30382): VFY: replacing opcode 0x6e at 0x001a
07-10 03:09:11.671: D/dalvikvm(30382): VFY: dead code 0x0006-0015 in Lst/jon/testKso;.onCreate (Landroid/os/Bundle;)V
07-10 03:09:11.671: D/dalvikvm(30382): VFY: dead code 0x001d-008f in Lst/jon/testKso;.onCreate (Landroid/os/Bundle;)V
07-10 03:09:11.681: D/dalvikvm(30382): VFY: dead code 0x009c-00a9 in Lst/jon/testKso;.onCreate (Landroid/os/Bundle;)V
07-10 03:09:11.701: D/AndroidRuntime(30382): Shutting down VM
07-10 03:09:11.701: W/dalvikvm(30382): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-10 03:09:11.761: E/AndroidRuntime(30382): FATAL EXCEPTION: main
07-10 03:09:11.761: E/AndroidRuntime(30382): java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
07-10 03:09:11.761: E/AndroidRuntime(30382): at st.jon.testKso.onCreate(testKso.java:37)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.os.Handler.dispatchMessage(Handler.java:99)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.os.Looper.loop(Looper.java:123)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.app.ActivityThread.main(ActivityThread.java:3683)
07-10 03:09:11.761: E/AndroidRuntime(30382): at java.lang.reflect.Method.invokeNative(Native Method)
07-10 03:09:11.761: E/AndroidRuntime(30382): at java.lang.reflect.Method.invoke(Method.java:507)
07-10 03:09:11.761: E/AndroidRuntime(30382): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-10 03:09:11.761: E/AndroidRuntime(30382): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-10 03:09:11.761: E/AndroidRuntime(30382): at dalvik.system.NativeStart.main(Native Method)
07-10 03:09:11.801: W/ActivityManager(76): Force finishing activity st.jon/.testKso
07-10 03:09:11.961: W/ActivityManager(76): Force finishing activity st.jon/.JonurActivity
07-10 03:09:12.472: W/ActivityManager(76): Activity pause timeout for HistoryRecord{405b45d0 st.jon/.testKso}
07-10 03:09:24.271: W/ActivityManager(76): Activity destroy timeout for HistoryRecord{405b4408 st.jon/.JonurActivity}
07-10 03:09:24.472: W/ActivityManager(76): Activity destroy timeout for HistoryRecord{405b45d0 st.jon/.testKso}
07-10 03:11:56.631: D/SntpClient(76): request time failed: java.net.SocketException: Address family not supported by protocol

Anonymous said...

07-10 03:09:11.631: E/dalvikvm(30382): Could not find class 'org.ksoap2.serialization.SoapObject', referenced from method st.jon.testKso.onCreate
07-10 03:09:11.631: W/dalvikvm(30382): VFY: unable to resolve new-instance 63 (Lorg/ksoap2/serialization/SoapObject;) in Lst/jon/testKso;
07-10 03:09:11.641: D/dalvikvm(30382): VFY: replacing opcode 0x22 at 0x0004
07-10 03:09:11.671: I/dalvikvm(30382): Could not find method org.ksoap2.serialization.PropertyInfo.setName, referenced from method st.jon.testKso.onCreate
07-10 03:09:11.671: W/dalvikvm(30382): VFY: unable to resolve virtual method 65: Lorg/ksoap2/serialization/PropertyInfo;.setName (Ljava/lang/String;)V
07-10 03:09:11.671: D/dalvikvm(30382): VFY: replacing opcode 0x6e at 0x001a
07-10 03:09:11.671: D/dalvikvm(30382): VFY: dead code 0x0006-0015 in Lst/jon/testKso;.onCreate (Landroid/os/Bundle;)V
07-10 03:09:11.671: D/dalvikvm(30382): VFY: dead code 0x001d-008f in Lst/jon/testKso;.onCreate (Landroid/os/Bundle;)V
07-10 03:09:11.681: D/dalvikvm(30382): VFY: dead code 0x009c-00a9 in Lst/jon/testKso;.onCreate (Landroid/os/Bundle;)V
07-10 03:09:11.701: D/AndroidRuntime(30382): Shutting down VM
07-10 03:09:11.701: W/dalvikvm(30382): threadid=1: thread exiting with uncaught exception (group=0x40015560)
07-10 03:09:11.761: E/AndroidRuntime(30382): FATAL EXCEPTION: main
07-10 03:09:11.761: E/AndroidRuntime(30382): java.lang.NoClassDefFoundError: org.ksoap2.serialization.SoapObject
07-10 03:09:11.761: E/AndroidRuntime(30382): at st.jon.testKso.onCreate(testKso.java:37)
07-10 03:09:11.761: E/AndroidRuntime(30382): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
07-10 03:09:11.761: E/AndroidRuntime(30382): at

Anonymous said...

Mr SeeSharpWriter i did all the steps and i still have these errors help me plz
thank in advance

Anonymous said...

by the way i am using the example in the top of this page

dilip said...

i got javadoc error in my program and i tried almost everything but i did not get any appropriate answer.

Guy Ballet said...

Thanks a lot for that useful tutorial !

Anonymous said...

Hi, I am new to android and using first the ksoap in my application. i work with the code that you had mentioned above. what i face the problem is that, when i

androidHttpTransport.call(SOAP_ACTION, envelope);

hit over this statement, it return's nothing or say blank, even the log's below this line has been printed on screen. Hope you understand my problem.
please help me out. thank you in advance. i am waiting for your response.

Anonymous said...

sorry , i correcting my statement, log's below the line has not been printed. its seems the above statement struck over on the server.

sunil Kuntal said...

Nice Tutorial !!
Does KSoap support Soap with WSHTTP binding ?
How can we make soap envelope with class inside a class (Complex soap envelope body )

SeeSharpWriter said...

@sunil Kuntal,

I don't know about WSHTTP binding.
The case with a class within a class I believe was covered by someone else in the comments.

ahmed sherif said...

thank you for your effort
I followed your steps but I have a problem :(
my android app give me an error when I run it like the application is stoped working here is my webserver code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

[WebService(Namespace = "http://vladozver.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]

public class Service : System.Web.Services.WebService
{
public Service () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public int GetSumOfTwoInts(int Operand1, int Operand2)
{
return Operand1 + Operand2;
}


}


and here is my android app code



package com.ahmed.webservice;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;


import org.ksoap2.*;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.Marshal;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

public class MainActivity extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String NAMESPACE = "http://vladozver.org/";
String METHOD_NAME = "GetSumOfTwoInts";
String SOAP_ACTION = "http://vladozver.org/GetSumOfTwoInts";
String URL = "http://192.168.1.1:49766/WebSite1/Service.asmx";


SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);

PropertyInfo pi = new PropertyInfo();
pi.setName("Operand1");
pi.setValue(2);
pi.setType(int.class);
Request.addProperty(pi);

PropertyInfo pi2 = new PropertyInfo();
pi2.setName("Operand2");
pi2.setValue(5);
pi2.setType(int.class);
Request.addProperty(pi2);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);


AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport(URL);




try
{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());
}
catch(Exception e)
{
e.printStackTrace();
}












}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;

}
}




please I need help :(

InfoChef said...

Hi sir this is my service(Asp.net and sqlserver) and am tried to access from the android application it shows that 'Connection exception localhost/127.0.0.1:80 connection refused' ,but if i am using some other url "http://grasshoppernetwork.com/NewFile.asmx";" it is working fine,is it necessary to host the service or anything i need to do

namespace Androidsectransmission
{
///
/// Summary description for Service1
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{


SqlConnection cn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=D:\\kumar works\\Androidsectransmission\\Androidsectransmission\\App_Data\\securedata.mdf;Integrated Security=True;User Instance=True");

[WebMethod]

public int Add(int a, int b)
{

return (a + b);
}

[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}

Android code :

package com.newws;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
public class CallSoap
{
public final String SOAP_ACTION = "http://tempuri.org/Add";

public final String OPERATION_NAME = "Add";

public final String WSDL_TARGET_NAMESPACE = "http://tempuri.org/";

public final String SOAP_ADDRESS = "http://localhost/Androidsectransmission/Service1.asmx";
public CallSoap()
{

}
public String Call(int a,int b)
{
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
PropertyInfo pi=new PropertyInfo();
pi.setName("a");
pi.setValue(a);
pi.setType(Integer.class);
request.addProperty(pi);
pi=new PropertyInfo();
pi.setName("b");
pi.setValue(b);
pi.setType(Integer.class);
request.addProperty(pi);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.setOutputSoapObject(request);

HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Object response=null;
try
{
httpTransport.call(SOAP_ACTION, envelope);
response = envelope.getResponse();
}
catch (Exception exception)
{
response=exception.toString();
}
return response.toString();
}
}



Anonymous said...

your blog is great for a beginner. thanks~ xD

Anonymous said...

Coming from C# background to java like yourself I was very appreciative of your blog and like you realized how much heavy lifting Msoft was doing for me.
Following your demo on KSoap2 above I am running into and object reference not set error. Full details are here.

http://stackoverflow.com/questions/14526892/ksoap2-soapobject-object-reference-not-set-to-an-instance

I don't understand what I am doing wrong / different from your example?

TIA
JB

LIfe is crazyy said...

hi.. i have made the web service to be running on the remote server and tried the same thing.. will that be possible in my case.

Arslan said...

hi when i run code there so many errors in logcat and no action is perform on button click
errors


error opening trace file: No such file or directory (2)
Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f080000}
Converting to string: TypedValue{t=0x12/d=0x0 a=2 r=0x7f080004}
Skipped 34 frames! The application may be doing too much work on its main thread.
Emulator without GPU emulation detected.
Skipped 33 frames! The application may be doing too much work on its main thread.
Skipped 110 frames! The application may be doing too much work on its main thread.
GC_CONCURRENT freed 107K, 8% free 2670K/2896K, paused 75ms+76ms, total 332ms
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
at libcore.io.IoBridge.connect(IoBridge.java:112)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
at java.net.Socket.connect(Socket.java:842)
at libcore.net.http.HttpConnection.(HttpConnection.java:76)
at libcore.net.http.HttpConnection.(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)

pliz answer me as soon as possible

Arslan said...

hi ... i got socket timeout exception ... dont know how to solve

anyone can help ....

thx

Anonymous said...

Hi,

I am using a complex datatype called InterBankData which has a variable called "amount" of double type. At runtime, I am getting an exception "Cannot Serialize: 555.54" when I pass a value of (say) 555.54 for amount. The java code of the InterBankData complex datatype is as follows:

package infybankservice;

import java.io.IOException;
import java.util.Hashtable;

import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.Marshal;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import android.app.Activity;

public class InterBankData implements KvmSerializable { //, Marshal {

public double amount;
public int fromAccountNum;
public String remarks;
public int toAccountNum;
public String toBankName;
public String transType;


public double getAmount() {
return amount;
}

public void setAmount(double amount) {
this.amount = amount;
}
public int getFromAccountNum() {
return fromAccountNum;
}
public void setFromAccountNum(int fromAccountNum) {
this.fromAccountNum = fromAccountNum;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public int getToAccountNum() {
return toAccountNum;
}
public void setToAccountNum(int toAccountNum) {
this.toAccountNum = toAccountNum;
}
public String getToBankName() {
return toBankName;
}
public void setToBankName(String toBankName) {
this.toBankName = toBankName;
}
public String getTransType() {
return transType;
}
public void setTransType(String transType) {
this.transType = transType;
}
@Override
public Object getProperty(int arg0) {
// TODO Auto-generated method stub
switch (arg0) {
case 0: return amount;
case 1: return fromAccountNum;
case 2: return remarks;
case 3: return toAccountNum;
case 4: return toBankName;

}
return null;
}

@Override
public int getPropertyCount() {
// TODO Auto-generated method stub
return 6;
}

@Override
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
// TODO Auto-generated method stub
switch (index) {
case 0:
info.type = Double.class;
info.name = "amount";
break;
case 1:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "fromAccountNum";
break;
case 2:
info.type = PropertyInfo.STRING_CLASS;
info.name = "remarks";
break;
case 3:
info.type = PropertyInfo.INTEGER_CLASS;
info.name = "toAccountNum";
break;
case 4:
info.type = PropertyInfo.STRING_CLASS;
info.name = "toBankName";
break;
case 5:
info.type = PropertyInfo.STRING_CLASS;
info.name = "transType";
break;
default: break;
}
}

@Override
public void setProperty(int index, Object value) {
// TODO Auto-generated method stub
switch (index) {
case 0:
amount = Double.parseDouble("value");
break;
case 1:
fromAccountNum = Integer.parseInt("value");
break;
case 2:
remarks = value.toString();
break;
case 3:
toAccountNum = Integer.parseInt("value");
break;
case 4:
toBankName = value.toString();
break;
case 5:
transType = value.toString();
break;

default: break;
}
}



}

Anonymous said...

Guys If you need to use this code you need to call web service async

http://stackoverflow.com/questions/3797478/threaded-web-service-call

Anonymous said...

Thanks for great post
don't for get to use PORT 10.0.2.2 on emulator

Vikas Singh said...

public class MainActivity extends Activity
{


String Url =null;
String SOAP_ACTION=null;
String Method_Name=null;
String Namespace=null;
SoapSerializationEnvelope envelope=null;

SoapObject Request=null;
AndroidHttpTransport androidHttpTransport=null;
EditText ip1=null;
EditText ip2=null;
TextView tv=null;
String a=null;
String b=null;


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
protected void onCreate(Bundle savedInstanceState)
{

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

StrictMode.setThreadPolicy(policy);




super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
Namespace = "http://tempuri.org/";
Method_Name = "GetSumOfTwoInts";
SOAP_ACTION = "http://tempuri.org/GetSumOfTwoInts";
Url = "http://192.168.116.1/webservice1/Service1.asmx";

Request = new SoapObject(Namespace, Method_Name);


//----------Layout part-------------------//

Button btn = (Button) findViewById(R.id.button);
ip1 = (EditText)findViewById(R.id.editText);
ip2 = (EditText)findViewById(R.id.editText2);
tv = (TextView) findViewById(R.id.textView3);
//---------Listener part----------------//


btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PropertyInfo pi = new PropertyInfo();
pi.setName("Operand1");
pi.setValue(2);
pi.setType(int.class);
Request.addProperty(pi);

PropertyInfo pi2 = new PropertyInfo();
pi2.setName("Operand2");
pi2.setValue(5);
pi2.setType(int.class);
Request.addProperty(pi2);


envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(Request);
androidHttpTransport = new AndroidHttpTransport(Url);


try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject)envelope.getResponse();
int result = Integer.parseInt(response.getProperty(0).toString());
tv.setText(Integer.toString(result));



} catch (Exception e) {
e.printStackTrace();
}

}
});


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}




I am getting following error:

24137-24137/com.cipher.acadsync W/System.err: java.lang.ClassCastException: org.ksoap2.serialization.SoapPrimitive cannot be cast to org.ksoap2.serialization.SoapObject
09-07 11:12:41.410

devika rani said...

Great blog,nice discussions on android applications

Mordechai Serraf said...

With regards to all your KSOAP2 android tutorials: THANK YOU SO MUCH! I appreciate what you have done here so very much, I was new to .Net and SOAP and average on Android and yet with your help I managed to get both sending and receiving (with complex objects) working perfectly in only a few days - for a full blown industry web service! This was for my first job and without your help I would have been in quite a bad position. You're the KSOAP2 batman! Thanks again.

Sqiar said...

Thanks a lot for sharing this with all folks you really recognise what you are talking about! In this complex environment business need to present there company data in meaningful way.Sqiar (http://www.sqiar.com/consultancy/tableau/) which is in UK,provide services like Tableau and Data Warehousing etc .In these services sqiar experts convert company data into meaningful way.

Dharma Kshetri said...

How to set and get soap header for security propose, but i am getting proper value fro wcf.


Actually , i spent lots of time for this. but couldnot find proper solution for getting soap header in android.

What i am doing in android look at this, I trying various method :

String NAMESPACE="http://tempuri.org/" ;

String SOAP_ACTION="http://tempuri.org/ISimpleCustomHeaderService/DoWork" ;

envelope.headerOut = new Element[3];
envelope.headerOut[0] = buildAuthHeader();

private Element buildSessionHeader() {
Element nodeElement = new Element().createElement(NAMESPACE, "web-node-id");
nodeElement.addChild(Node.TEXT, "node");
return nodeElement;
}

private Element buildNodeIDHeader() {
Element sessionElement = new Element().createElement(NAMESPACE, "web-session-id");
sessionElement.addChild(Node.TEXT, "session");
return sessionElement;
}

private Element buildUserHeader() {
Element userElement = new Element().createElement(NAMESPACE, "web-user");
userElement.addChild(Node.TEXT, "user");
return userElement;
}

================================================================

envelope.headerOut[0] = buildAuthHeader();
------------------
private Element buildAuthHeader() {
String test = "ns";
Element h = new Element().createElement(NAMESPACE, "Header");
Element first = new Element().createElement(NAMESPACE, "web-user");
first.addChild(Node.TEXT, "web_user_name");
h.addChild(Node.ELEMENT, first);

Element second = new Element().createElement(NAMESPACE, "web-node-id");
second.addChild(Node.TEXT, "web_node_id");
h.addChild(Node.ELEMENT, second);

Element third = new Element().createElement(NAMESPACE, "web-session-id");
third.addChild(Node.TEXT, "web_session_id");
h.addChild(Node.ELEMENT, third);
return h;
}

====================================================

List headerList=getHeaderList();
------------
androidHttpTransport.call(SOAP_ACTION, envelope,headerList);
---------------
private List getHeaderList() {
List headerList = null;
try {

headerList = new ArrayList();
// String security=HeaderUserName+":"+HeaderPassword;
// headerList.add(new HeaderProperty("Authorization", "Basic " + org.kobjects.base64.Base64.encode(security.getBytes())));
headerList.add(new HeaderProperty("web-user", "user Id"));
headerList.add(new HeaderProperty("web-node-id","node id"));
headerList.add(new HeaderProperty("web-session-id","session id"));
}catch (Exception e) {
e.printStackTrace();
}
return headerList;
}

androidHttpTransport.call(SOAP_ACTION, envelope,headerlist);

=========================================== and

Element[] header = new Element[1]; header[0] = new
Element().createElement("http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd","Security");

Element ws = new Element().createElement(null, "web-user");
ws.addChild(Node.TEXT, "First");
Element wni = new Element().createElement(null, "web-node-id");
wni.addChild(Node.TEXT,"Second");
Element wsi= new Element().createElement(null, "web-session-id");
wsi.addChild(Node.TEXT,"Third");
header[0].addChild(Node.ELEMENT, ws);
header[0].addChild(Node.ELEMENT, wni);
header[0].addChild(Node.ELEMENT, wsi);
// add header to envelope
envelope.headerOut = header;

Please suggest me what is method above correct set soap header

Would you recommend me how to get soap header in c#.

Post a Comment