Saturday, April 7, 2012

Android Web service Access Tutorial

Updated tutorial for new versions >> http://codeoncloud.blogspot.com/2013/06/android-java-soap-web-service-access.html

This simple example demonstrates how we can access a java web service  from Android application.
We can't connect Android 3.0 and after versions to the internet in the main thread. So we have to start new thread. In this tutorial I'm going to demonstrate how we can access a simple java web service  by starting new thread. I have tested this on Android 4.0.3 platform.

Following is the sample java code for web service class. Deploy this web service on Tomcat server at local host. To implement this web service follow these posts.
1. Create java web service in Eclipse using Axis2 (Part 01)
2. Create java web service in Eclipse using Axis2 (Part 02) 

package com.android.ws;
public class PrintMsg {
 public String sayHello(){
           return "Hello Chathura";
        }
}
Here is the code for Android application to invoke deployed web service.
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.widget.TextView;
import android.app.Activity;
import android.os.Bundle;
 
public class AndroidWSClientActivity extends Activity {
  
    private static final String SOAP_ACTION = "http://ws.android.com/sayHello";
    private static final String METHOD_NAME = "sayHello";
    private static final String NAMESPACE = "http://ws.android.com/";
    private static final String URL = "http://175.157.229.119:8080/AndroidWSTest/services/PrintMsg?wsdl";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
      
    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();
  }
 }
}

Note:
SOAP_ACTION in line 13 is "NAMESPACE/METHOD_NAME".

METHOD_NAME
in line 14 is WSDL operation. You can find something like <wsdl:operation name="sayHello"> in your WSDL sayHello is METHOD_NAME here.

NAMESPACE in line 15 is targetNamespace in the WSDL. Replace that & add a "/" to the end .

URL in line 16 The URL of WSDL file. In my case it is http://175.157.229.119:8080
/AndroidWSTest/services/PrintMsg?wsdl
blue colored is the ip of the server replace it with your ip & red colored is the port number.

Make appropriate changes according to your WSDL. I think it is easy to find those things if you open WSDL from a web browser. For more details look the image :



  
Add Internet permission to Androidanifest.xml file.(Look highlighted line)

    
    
        
            
                
                
            
        
    


}



Run the application using Emulator.
Result :


You can download updated project here here
Password :cloud

 
If you find this post helpful don't forget to leave a comment. Your comments always encourage me!

79 comments:

  1. hi
    i'm Rushit,

    C:Build path entry is missing: C:Users/HP/Documents/ksoap2-android-assembly-2.5.8-jar-with-dependencies(1).jar

    how to resolve it ?

    ReplyDelete
    Replies
    1. You have to remove imported ksop2 library in my project first and then re import ksoap2 from your hard disk. This will solve your problem.
      Sorry for the late reply!

      Delete
  2. I 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.

    ReplyDelete
  3. I 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

    ReplyDelete
    Replies
    1. Please mail me full stack trace to priyankarahac@gmail.com I'll check.

      Delete
  4. Hi.,
    These tutorial is successfully worked on emulator.but not worked on my device.version is 2.2.my emulator version also 2.2 only.why my device is not supported.

    ReplyDelete
    Replies
    1. For 2.2 test this http://javatutorialspoint.blogspot.com/2012/02/android-web-service-access-using-ksoap2.html

      Delete
  5. I am getting error Fatal Exception, Could not find class org.ksoap2.serialization.SoapObject referenced from method com.android.ws.AndroidWSClientActivity$1.run

    on SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    In URL do I need to make any changes? Please help me.

    ReplyDelete
    Replies
    1. Yes you have to change the URL, first create a web service and use the URL with your ip, but the error you mentioned above is not because of the URL error just try this and see whether you can solve the problem

      1. Create a directory on root in your project named libs
      2. copy and paste ksop 2.6.5 jar into libs dir.

      Check this!

      Delete
  6. I am getting error Fatal Exception, Could not find class org.ksoap2.serialization.SoapObject referenced from method com.android.ws.AndroidWSClientActivity$1.run

    on SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    In URL do I need to make any changes? Please help me.

    ReplyDelete
    Replies
    1. First of all remove jar files & then you should put the jar files in the workspace of your current working project directory it can be lib. or any other of your choice & then configure your build path again....

      Hope it will help you !!!!!!!Pawan Soni

      Delete
    2. first download these files
      ksoap2-android-assembly-2.4-jar-with-dependencies.jar
      ksoap2-j2me-core-2.1.2.jar

      then right click on project>build path>Add External Archives..
      select these files which u have downloaded..

      then again right click on project>properties>java build path select Libraries tab and remove all the crossed jar files..
      its done.

      Delete
    3. u r using above 3.0 version android ..... in dis u need to delete the ksoap jar files from and then just copy jar file and paste in lib folder .... i hope its clear

      Delete
  7. Hi Chathura,

    I want to pass two arguments in the method from my android code only. Can you please help me with it?

    ReplyDelete
  8. Try this post http://codeoncloud.blogspot.com/2012/04/android-web-service-access-tutorial.html

    ReplyDelete
  9. Hey Thanks for the post...
    Now its not able to connect to localhost. It is throwing ConnectException. I have given the permission in android Manifest also. Still it is not getting connected. What to do?

    ReplyDelete
    Replies
    1. In your manefiest file copy this

      but always remember it should be before tag

      Hope it will help you !!! Pawan Soni

      Delete
    2. Dear Pawan,
      You mentioned "in your manifest file, copy this..".
      I am slightly confused what 'this' means and also what should be before tag.
      I guess some part went missing. Can you please elaborate?
      Thanks,
      Niks

      Delete
  10. This sounds strange.
    What is the Android version you have used ?

    ReplyDelete
  11. hi..dude.. i am laxman i am start new career in android..becoz i dn't much more on webservice ..plz send me complete tutorial to the my mail."laxman.k1223@gmail.com"

    ReplyDelete
  12. If you are going for best contents like I do, only visit this website daily
    since it presents feature contents, thanks
    Here is my website ; games for android

    ReplyDelete
  13. Hi , dude, i am new in android, i had develop same application using this blog but when i am executing my program that time i am unable to see anything , means blank screen , how i will resolve my problem, i am using android 4.1 and tomcat 6.0 , axis 2.0..

    ReplyDelete
    Replies
    1. I just had the same problem. I finally figured out to turn off the tomcat server and then launch the app. Turn the server back on, create the webservice again, run on the server, and start the app again.

      Kyle

      Delete
  14. Hi Chathura,
    I am using webservice,which works fine in 2.2 and 2.3 version but not in 4.0 and higher versions. Here's 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.HttpTransportSE;

    import android.util.Log;

    public class WebService {

    private final String NAMESPACE ="http://aaaaaa.org/";
    private final String URL ="http://5xxxxxxxxxxx.asmx?WSDL";






    public boolean checkUser(String _EmailID, String _Password) {


    boolean result = false;

    final String SOAP_ACTION ="http://aaaaaaaa/Login";
    final String METHOD_NAME = "Login";

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo propertyInfoEmail = new PropertyInfo();
    propertyInfoEmail.setName("_EmailID");
    propertyInfoEmail.setValue(_EmailID);
    propertyInfoEmail.setType(String.class);
    request.addProperty(propertyInfoEmail);

    PropertyInfo propertyInfoPassword = new PropertyInfo();
    propertyInfoPassword.setName("_Password");
    propertyInfoPassword.setValue(_Password);
    propertyInfoPassword.setType(String.class);
    request.addProperty(propertyInfoPassword);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true; // put this only if the web service is .NET one
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
    androidHttpTransport.call(SOAP_ACTION, envelope);
    SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
    Log.i("myApp", response.toString());
    if(response.toString().equalsIgnoreCase("true")){
    result = true;
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }


    What should i change here for higher versions? please help me.....

    ReplyDelete
    Replies
    1. This post explains how we can access the web from Android 3.0 and the versions released after that please check. This information will help you.
      http://codeoncloud.blogspot.com/2012/04/android-403-webservice-access-tutorial.html

      Delete
  15. Hi chathura,
    I'm trying to invoke a public web service via KSOAP(2.5.8). But it is not able to get data from service for ice-cream sandwich versions. It work's fine in lower versions like 2.2 and 2.3. Here's 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.HttpTransportSE;

    import android.util.Log;

    public class WebService {

    private final String NAMESPACE ="http://aaaaaa.org/";
    private final String URL ="http://5xxxxxxxxxxx.asmx?WSDL";






    public boolean checkUser(String _EmailID, String _Password) {


    boolean result = false;

    final String SOAP_ACTION ="http://aaaaaaaa/Login";
    final String METHOD_NAME = "Login";

    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

    PropertyInfo propertyInfoEmail = new PropertyInfo();
    propertyInfoEmail.setName("_EmailID");
    propertyInfoEmail.setValue(_EmailID);
    propertyInfoEmail.setType(String.class);
    request.addProperty(propertyInfoEmail);

    PropertyInfo propertyInfoPassword = new PropertyInfo();
    propertyInfoPassword.setName("_Password");
    propertyInfoPassword.setValue(_Password);
    propertyInfoPassword.setType(String.class);
    request.addProperty(propertyInfoPassword);

    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    envelope.dotNet = true; // put this only if the web service is .NET one
    envelope.setOutputSoapObject(request);
    HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

    try {
    androidHttpTransport.call(SOAP_ACTION, envelope);
    SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
    Log.i("myApp", response.toString());
    if(response.toString().equalsIgnoreCase("true")){
    result = true;
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    return result;
    }

    What should i change in above code? please help me....

    ReplyDelete
  16. whoah this blog is magnificent i love studying your posts. Stay up the great work!

    You understand, many individuals are looking around for this information, you can help them greatly.
    Also see my page - more info

    ReplyDelete
  17. The blog and data is excellent and informative as well.
    one click root download

    ReplyDelete
  18. Thanks a bunch for sharing this with all folks you really recognize what
    you're talking about! Bookmarked. Please additionally talk over with my site =). We will have a hyperlink trade contract among us
    Also see my page > Closing Unused Credit Accounts May Help Your Credit Rating

    ReplyDelete
  19. I am genuinely grateful to the holder of this web page who has shared this impressive post
    at at this time.
    Check out my weblog ... kent nanotek

    ReplyDelete
  20. Hey are using Wordpress for your blog platform?
    I'm new to the blog world but I'm trying to get started and create my own.
    Do you need any html coding expertise to make your own blog?
    Any help would be greatly appreciated!
    Here is my weblog : nat sherman cigars

    ReplyDelete
  21. Awesome article.
    Stop by my web-site losless music download

    ReplyDelete
  22. Wow, wonderful blog layout! How long have you been blogging for?
    you make blogging look easy. The overall look of your site is magnificent, as well as the content!
    Here is my web site ; cigarettes online

    ReplyDelete
  23. Thank you for the great tutorial once again. Keep up the good work!

    Kyle

    ReplyDelete
  24. I'll immediately grasp your rss as I can't in finding
    your email subscription link or e-newsletter service.
    Do you have any? Please allow me recognize in order that I may just subscribe.
    Thanks.
    Also see my web page > buy cigarettes online uk

    ReplyDelete
  25. I will immediately take hold of your rss feed as I can
    not in finding your email subscription link or e-newsletter service.
    Do you have any? Please let me recognise in order that I may just subscribe.

    Thanks.
    Feel free to surf my weblog how to speed up computer

    ReplyDelete
  26. I do not know if it's just me or if everybody else experiencing issues with your website. It looks like some of the written text in your posts are running off the screen. Can somebody else please provide feedback and let me know if this is happening to them as well? This may be a issue with my internet browser because I've
    had this happen before. Appreciate it
    My website > how to talk to girls

    ReplyDelete
  27. I don't even know how I ended up here, but I thought this post was good. I don't know who you
    are but definitely you're going to a famous blogger if you aren't already ;) Cheers!
    Here is my website ; speed up my computer

    ReplyDelete
  28. I write a leave a response each time I especially enjoy a article on a website or I have something to add to the conversation.
    It's triggered by the passion communicated in the post I browsed. And on this post "Android Web service Access Tutorial". I was actually moved enough to post a leave a responsea response ;) I do have a couple of questions for you if you tend not to mind. Could it be just me or does it appear like a few of the comments come across as if they are coming from brain dead people? :-P And, if you are writing on additional online social sites, I'd like to follow
    you. Would you list every one of your social pages like your linkedin profile,
    Facebook page or twitter feed?
    Feel free to visit my web blog ; buy youtube views

    ReplyDelete
  29. We returned to check on everything you are writing this time around.
    Review my webpage - losless music download

    ReplyDelete
  30. I’m a lengthy time watcher and I just considered I’d drop by and say hello there for the really first time.

    I severely take pleasure in your posts. Many thanks
    That you are my role models. Thanks for that article
    Feel free to surf my web page - http://howto.getfairskin.com/simple-ways-to-get-fair-skin

    ReplyDelete
  31. hii...

    whn i run the android app i get a blank screen...evrythng including web service and all is ok...do u know hw to solve ths problem?

    ReplyDelete
  32. hi..
    i am looking for pass the class object as a parameter through ksop2 to dot net web service, plz help me

    ReplyDelete
  33. hi chatura,

    I am Rachel, I was just started learning android..I want to access my database. I was using PhpMysql.I was also try your codes above but i am having a problem with the NAMESPACE/METHODNAME i dont know how to find it..


    How do i find my WSDL..please help Chatura...i also dont know the URL

    ReplyDelete
  34. hii

    when i run the android app and click the button to navegate to other screen it says sorry the application has stop unexpectedly..
    i check my codes and theirs no error occur...
    please help..thanks

    ReplyDelete
    Replies
    1. Did you define your new activity in the manifest.xml ??

      Delete
  35. [2012-12-03 13:38:33 - SendValues] Project has no default.properties file! Edit the project properties to set one.

    how to solve this error

    ReplyDelete
  36. Thanks for your marvelous posting! I quite enjoyed reading it, you happen to be a great
    author.I will be sure to bookmark your blog and will often come back later on.
    I want to encourage you continue your great posts, have a nice
    weekend!
    Also visit my blog :: Elitecigarettestore.Com

    ReplyDelete
  37. Hi, Can you create a post about transfer an image in SOAP?

    ReplyDelete
  38. when i open my application in android am just getting blank screen without any output..:( what shuld i do for tis?? help me pls..

    ReplyDelete
  39. After looking into a handful of the articles on your site, I honestly appreciate your technique of
    writing a blog. I book marked it to my bookmark website list and will be checking back
    soon. Please check out my website as well and tell me your opinion.
    Also visit my web blog discount cigarettes

    ReplyDelete
  40. it is showing a "force close " when i run the android part in my phone.

    "http://localhost:8080/TestProperties/services/TestPropts?wsdl" works but "http://localhost:8080/TestProperties/services/TestPropts?wsdl" is not working, saying cannot find page. i m running server side on eclipse juno. i m stucked in this for last 5 days.. plz find me a solution for this

    ReplyDelete
  41. Please help me I want wsdl file for this project..i m waiting for ur reply..
    thanks in advance...

    ReplyDelete
  42. Unable to sendViaPost to url[http://localhost:8087/AndroidWSTest/services/Version] error came wenever I run the web service wt can I do for solve tat pls help me!!!

    ReplyDelete
  43. I want web service code. if any body having running web service and android code please sent to my mail id because I want to submit my project with in 2days.this is my mail id iyappan689@gmail.com.pls help me friends.
    thanks in advance....

    ReplyDelete
  44. you can simple use http://www.wsdl2code.com to parse connect and recieve data from web services...

    ReplyDelete
  45. Hello Chathura.. nice work ..I am getting an error below:
    Fatal Exception:Thread-147
    java.lang.NoClassDefFoundError: org.ksoap.serialization.SoapObject

    ReplyDelete
  46. Nice work Chathura.. I have followed same steps you given ..But getting error
    Fatal Exception :Thread-147
    java.lang.NoClassDefFoundError:org.ksoap2.serialization.SoapObject

    ReplyDelete
  47. wooaaaaahhhh.This is fascinatinggg dudee.respecttttttt!!

    ReplyDelete
  48. Woaaaaahh.This is fascinatinggg.Thank you dude.respect!

    ReplyDelete
  49. hi ... my ksoap code is not showing any result .... webservice is running perfectly but response is still empty ...
    i am using visual studio 2008 ... do i need to publish my webservice on iis server or not ???

    ReplyDelete
  50. hi .... em using ur code but still ksoap response is still empty ..... do i need to publish my webservice on iis and i am using visual studio 2008.....

    ReplyDelete
  51. With java axis2 web service :tomcat 7.0 and axis 1.6.2 , android 4.0 response is permission denied! With .net web service it works. Some help...:-(

    ReplyDelete
  52. with java web service axis2 i m getting error permission denied. .NET web service works fine. Some help...?

    ReplyDelete
  53. i tried everything as specified by your tutorial. but my application unfortunately stops, what is the reason? please help. i followed your steps as specified. please help

    ReplyDelete
  54. hi. i did all the steps as given by you. but still i cant get output. my application unfortunately stops. please help.

    ReplyDelete
  55. Sir How to pass parameters for sayHello(String name) ?

    ReplyDelete
  56. how to get image in android from asp.net web service uisng ksoap in base64String formate..plz reply me as soon as possiable

    ReplyDelete
  57. Hai Sir...

    i had workout java webservices in android working fine .when create webservices as .net platform its not getting its shows exception .can u help me out .net webservice with android..please send me some sample code for it..

    thanks and regards
    prakash
    prakaz25@gmail.com

    ReplyDelete
  58. I want to make an application in which there will be a button named as locator,when i click on button then it show latitude and longitude of that particular location,means to say that i need the coding of Activity.java to develop gps locator application.so plzzz help me

    ReplyDelete
  59. Share market and commodity market is largest market in the world here are millions of people are investing. But How many people getting profit only some people because they don't get the tips about share market. They work according to own thinking. They don't take expert advice. Now we offer stock market tips or share market tips like Commodity Tips, Mcx calls and more.
    Thank you

    ReplyDelete
  60. I have a problem, using your code, for getting data from wcf webservices, here is the problem in stackoverflwo that i already posted: http://stackoverflow.com/questions/23076478/how-to-connect-wcf-in-android-but-unable-to-get-response

    ReplyDelete
  61. Help me,How can we get android autoCompleteText data from ksoap webservice, Fetching Data From Webservcie Working Fine, i Want to show data in Autocomplete textview or suggestion in Edittext.

    ReplyDelete