In this tutorial I'm going to demonstrate how we can access a java web service in Android application using ksoap2 library. This Android application also passes parameters to the web service.
First we have to create a web service & deploy it on Tomcat server.
Here is the sample code of java web service I'm going to access.
package com.testprops.ws; public class TestPropts { public String testMyProps(String fname,String lname){ return "First Name : "+fname+" Last Name : "+lname; } }
Android application will pass parameters for fname & lname variables.
To create web service refer my these tutorials.
1. Create java web service in Eclipse using Axis2 (Part 01)
2. Create java web service in Eclipse using Axis2 (Part 02)
Following is the code for the Android application which invoke the web service. You have to use ksoap2 (You can download ksoap2 from here:::http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2) library for this implementation. Read my comments carefully
package com.sendproperties.ws; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class SendValuesActivity extends Activity { private final String NAMESPACE = "http://ws.testprops.com"; private final String URL = "http://175.157.143.117:8085/TestProperties/services/TestPropts?wsdl"; private final String SOAP_ACTION = "http://ws.testprops.com/testMyProps"; private final String METHOD_NAME = "testMyProps"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); String firstName = "Android"; String lastName = "Program"; //Pass value for fname variable of the web service PropertyInfo fnameProp =new PropertyInfo(); fnameProp.setName("fname");//Define the variable name in the web service method fnameProp.setValue(firstName);//Define value for fname variable fnameProp.setType(String.class);//Define the type of the variable request.addProperty(fnameProp);//Pass properties to the variable //Pass value for lname variable of the web service PropertyInfo lnameProp =new PropertyInfo(); lnameProp.setName("lname"); lnameProp.setValue(lastName); lnameProp.setType(String.class); request.addProperty(lnameProp); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); try { androidHttpTransport.call(SOAP_ACTION, envelope); SoapPrimitive response = (SoapPrimitive)envelope.getResponse(); TextView tv = new TextView(this); tv.setText(response.toString()); setContentView(tv); } catch (Exception e) { e.printStackTrace(); } } }
You can find complete information about the implementation of Android application from these two posts.
1. Create java web service in Eclipse using Axis2 (Part 01)
2. Create java web service in Eclipse using Axis2 (Part 02)
Change these things in your Android program according to your web service
NAMESPACE in line 15 is targetNamespace in the WSDL.
blue colored is the ip of the server replace it with your ip & red colored is the port number.
SOAP_ACTION in line 17 is "NAMESPACE/METHOD_NAME"
METHOD_NAME in line 18 is WSDL operation. You can find something like <wsdl:operation name="............."> in your WSDL.
METHOD_NAME in line 18 is WSDL operation. You can find something like <wsdl:operation name="............."> in your WSDL.
Make appropriate changes according to your WSDL. Open your WSDL using Firefox or Chrome. Then you can easily find those values from the WSDL.
We have to add internet permission to the Android Manifest. After adding permission your Manifest should like follows.
Here is the final result
You can download sample projects:
Click here to download web service project
Click here to download Android project
If you find this post helpful don't forget to leave a comment. your comments encourage me to write!
that was realy help full ,thanks man..
ReplyDeleteI am using 2.2 version so i did not start a new thread. I some how fail to run a webservice though i gave the name space , method , url correct. I get this strangeorg.xmlpull.v1.XmlPullParserException: attr value delimiter missing! (position:START_TAG . Please help
ReplyDeleteIf you can mail your project. I'll check... my gmail id is priyankarahac
DeleteI think it is better if you first try for this :::::http://javatutorialspoint.blogspot.com/2012/02/android-web-service-access-using-ksoap2.html
I solved this problem just removing "?wsdl" from URL.
Deletekya jhant Code hai,Its Have sm problm
DeleteThe Source code never excute
How i should use flag counter in my drupal based web site..
DeleteLike you used in this page..
Please Revert me on gaurank24@yahoo.com
Thanks In Advance
Plz tell me how i should flag counter on my drupal based web site
Deletemy id is gaurank24@yahoo.com
Thanks In Advance
how to send values to mysqldatabase using userinterface textbox in android.
ReplyDeleteCheck my new post http://codeoncloud.blogspot.com/2012/07/android-mysql-client-part-2.html
Deletehow to store valuse in mysql database using UserInterface TextBox in android(ksoap2)
ReplyDeleteThis post will help you
Deletehttp://codeoncloud.blogspot.com/2012/07/android-mysql-client-part-2.html
how to store values in MySql database using UserInterface TextBox in Android(ksoap2)
ReplyDeleteCheck this post http://codeoncloud.blogspot.com/2012/07/android-mysql-client-part-2.html
DeleteHey I know this is off topic but I was wondering if
ReplyDeleteyou knew of any widgets I could add to my blog that automatically tweet my newest
twitter updates. I've been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this. Please let me know if you run into anything. I truly enjoy reading your blog and I look forward to your new updates.
Here is my web site :: Likejor
I absolutely love your blog and find most of your post's to be exactly what I'm looking for.
ReplyDeleteCan you offer guest writers to write content
for you personally? I wouldn't mind composing a post or elaborating on a few of the subjects you write in relation to here. Again, awesome site!
My web-site : Gazebos For Sale
Your contents are more then sufficient for me.
ReplyDeletesuper one click root
For me nothing works, just like 99,9% of examples for android on internet...
ReplyDeleteDoes not work for me.
ReplyDeleteI am very thankful to all your team for sharing such inspirational information.
ReplyDeleteone click root software
I hv created webwervice usind CXF framework, wat shud i do to access the same webservice in android?
ReplyDeleteHi guys, this tutorials also help using webservices android
ReplyDeletehttp://www.mobengineers.com/2012/11/xml-parsing.html
I have run ur project but some errors in org.ksoap2 import statement wt can I do for tat?
ReplyDeleteGo to Project properties and select java build path of the imported project to the Eclipse work space, then select add external jars tab and remove already imported ksoap jar and re-import ksoap from your computer hard disk.
Deletethanks for the help. Now in emulator unfortunately sendvalues has stopped error message coming what can I do now?
Deletethanks in advance...
i had the same error if you got a solution please tel me about it
DeleteInitially set the web service server.
ReplyDeleteI run the test properties->Run on server>http://localhost:8081/TestProperties/
was loaded in the Axis 2 home in that welcome message came.
Then run the send values activity project as Android Application.
In the emulator unfortunately sendvalue has stopped message coming what is the reason for that? please help me......
HI I WANT TO CAL WEBSERVICES IN MY LISTVIEW PROJECT ..FOLOWING IS THE CODE ..BUT WEN I RUN IT ..ITS CALLING WEBSERVICES BUT NOT IN THE RITE MANNER..HERE IS THE CODE PLEASE HELP ME..
ReplyDeletepackage fin.al;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class FinalwebservicesActivity extends Activity {
// private static final String NAMESPACE = "com.service.ServiceImpl";
// private static final String URL =
// "http://192.168.202.124:9000/AndroidWS/wsdl/ServiceImpl.wsdl";
// private static final String SOAP_ACTION = "ServiceImpl";
// private static final String METHOD_NAME = "message";
private static String SOAP_ACTION = "http://tempuri.org/GetAllContinentals";
// private static String SOAP_ACTION2 =
// "http://tempuri.org/GetCountryByContinentals";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME = "GetAllContinentals";
// private static String METHOD_NAME2 = "GetCountryByContinentals";
private static String URL = "http://38.99.250.24/trackmyvisit/AndroidService.asmx";
static String ContitnentalsID, ContinentalsName;
static String errorCode = "", errorDescription = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
TextView tv = new TextView(this);
tv.setText(response.toString());
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
}
hi sir,with the help of ur code i was able to connect and call web services ..but the way its showing is not coreect...please help me..i want the continents to come in a list view..
ReplyDeletepackage fin.al;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class FinalwebservicesActivity extends Activity {
// private static final String NAMESPACE = "com.service.ServiceImpl";
// private static final String URL =
// "http://192.168.202.124:9000/AndroidWS/wsdl/ServiceImpl.wsdl";
// private static final String SOAP_ACTION = "ServiceImpl";
// private static final String METHOD_NAME = "message";
private static String SOAP_ACTION = "http://tempuri.org/GetAllContinentals";
// private static String SOAP_ACTION2 =
// "http://tempuri.org/GetCountryByContinentals";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME = "GetAllContinentals";
// private static String METHOD_NAME2 = "GetCountryByContinentals";
private static String URL = "http://38.99.250.24/trackmyvisit/AndroidService.asmx";
static String ContitnentalsID, ContinentalsName;
static String errorCode = "", errorDescription = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
TextView tv = new TextView(this);
tv.setText(response.toString());
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
}
also on the click of any of the continents the following countries should come in listview..please help me..i have tried a lot..cz of lack of guidence i am not bale to perform..
ReplyDeleteCvp reponse exacte pour cette application:
ReplyDeletecomment en peut fait communication entre l'application Android et base des données avec q'uelle technologie ( avec http ou quoi d'autre...) en pluse lorsque telephonne ne contient pas connexion internet comment en peut fait la communication
Rq:je préféré un aidée qui accumule tout le personne (avec telphone qui contient connexion ou nn ) cvp reponse exacte
Cvp reponse exacte pour cette application:
ReplyDeletecomment en peut fait communication entre l'application Android et base des données avec q'uelle technologie ( avec http ou quoi d'autre...) en pluse lorsque telephonne ne contient pas connexion internet comment en peut fait la communication
Rq:je préféré un aidée qui accumule tout le personne (avec telphone qui contient connexion ou nn ) cvp reponse exacte
How to download the lib file,in your source file,library is not there,
ReplyDeleteYou can download ksoap2 from here
Deletehttp://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2
In your source file,there is no lib file,how to get that libray file
ReplyDeleteLib file.. yeah its there .. k soap..
ReplyDeleteLib file.. yeah its there .. k soap..
ReplyDeleteI am facing an error:
ReplyDeleteandroid.app.ServiceConnectionLeaked: Service com.android.exchange.ExchangeService has leaked ServiceConnection com.android.emailcommon.service.ServiceProxy$ProxyConnection@40d09c70 that was originally bound here
how to solve it.......
hi......here i am posting my code emulator is unable to connect to the webservice but my web service is working fine i checked with the client code.
ReplyDeletehi....chathura,
ReplyDeletemy emulator is unable to connect to the webservicce but my webservice is working fine.here i am posting my code..........
package com.example.webapp;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String SOAP_ACTION = "http://ws.android.org/sayHello";
private static final String METHOD_NAME = "sayHello";
private static final String NAMESPACE = "http://ws.android.org/";
private static final String URL = "http://localhost:8080/android/services/Printmsg?wsdl";
@Override
protected void onCreate(Bundle savedInstanceState)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.setThreadPolicy(policy);
Button submit = (Button) findViewById(R.id.Submit);
submit.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
serviceAction();
}
});
}
private void serviceAction()
{
TextView result = null;
Thread networkThread = new Thread() {
@Override
public void run() {
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
ht.call(SOAP_ACTION, envelope);
final SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
final String str = response.toString();
runOnUiThread (new Runnable(){
public void run() {
TextView result;
result = (TextView)findViewById(R.id.textView1);//Text view id is textView1
result.setText(str);
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
};
networkThread.start();
}
@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;
}
}
Hi Chathura,
ReplyDeleteI want to upload web service and database to Server run online,
how can I do this ? Thanks...
I want to upload web service and database to Server run online,
ReplyDeletehow can I do this ? Thanks...
Hai i want to get data from webserver database using my android application how to do it this action please help me...
ReplyDeleteHi, Designing websites is the primary task which every web owner will be looking for Web Design Cochin into as their primary step to web success.Thanks...........
ReplyDeleteYou did really job on your blog,i love your blog style,and how you make your point on this article ,cool.
ReplyDeleteaviator sunglasses
Thanks for the nice and interesting Tut.
ReplyDeleteCan you post another Tut for the SOAP which has the default authentication.
Means in order to call a even method user has to pass the Credential.
Thanks again.
Practice important android interview questions @ http://skillgun.com
ReplyDeleteThanks for such a clear and helpful tutorial. I implemented a web service and accessed it successfully from an android application.But when i tried accessing another web service from the same android application, the following error occurs.
ReplyDelete[ERROR] The endpoint reference (EPR) for the Operation not found is http://10.0.2.2:8080/Plaza2/services/AvrPlazaImplementation and the WSA Action = http://plazaimplementation.Avrimplementation.org/saveFeedback. If this EPR was previously reachable, please contact the server administrator.
I checked the url of wsdl in browser and it worked fine.
Thanks in advance
Why I am getting failed to connect to /10.0.0.2 (PORT 8080) after 20000ms error.
ReplyDeleteMy web service is in my local host and I am running my android program on emulator.
My program is bit different and it is passing two integers to add them at the server.
Thank you for sharing the useful article..Am got the best information..
ReplyDeleteBest Website Designing Services Bangalore | Best Website Development Companies Bangalore