2013年11月21日星期四

How to Call Web Service in Android Using SOAP

Introduction

In this tutorial, we will learn how to call a Web Service using SOAP (Simple Object Access Protocol). 

Prerequisites

Web Service, SOAP envelope, WSDL (Web Service Definition Language)

What is SOAP?

SOAP is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission. The following is the structure of SOAP Envelope:

AndWeb1.jpg

Step 1:

First create a "New Android Project". Name it "WebServiceDemo" like below.

AndWeb2.jpg

AndWeb3.jpg

AndWeb4.jpg

Step 2:

Now right-click on your "WebServiceDemo" project and select "New -> Folder"

AndWeb5.jpg


Now, give it a name it "lib". We need to add a SOAP library into this directory.

AndWeb6.jpg

Step 3:

Now download the attached library named "ksoap2-android-assembly-2.6.0-jar-with-dependencies.jar". Copy that file and paste it into the "lib" directory.

After copying, do the following steps:
  1. Right-click on the project.
  2. Go "Build Path -> Configure Build Path"

    AndWeb7.jpg
     
  3. Now, click on "Add Jars" and select ".jar" file from "project -> lib" directory.

    AndWeb8.jpg
     
  4. Click on "Ok" to finish the procedure of adding library to Android application.
Step 4:

Next we need to create a layout of screen. To do so, go to "WebServiceDemo -> res -> layout -> main.xml"
Open this xml file in editing mode, and place below code.

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fahrenheit"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/txtFar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Celsius"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/txtCel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/btnFar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="Convert To Celsius" />

        <Button
            android:id="@+id/btnCel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="Convert To Fahrenheit" />

    </LinearLayout>


    <Button
        android:id="@+id/btnClear"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Clear" />

</LinearLayout>

This will create simple following screen.

AndWeb9.jpg


Step 5:

Now, find out any Web Service, make sure that you can view its WSDL file by writing "?wsdl" after that address.

For example, you have a web service like http://www.w3schools.com/webservices/tempconvert.asmx",  so to view the WSDL file, simply write "?wsdl" after this address like:
http://www.w3schools.com/webservices/tempconvert.asmx?WSDL".  

You are now done with the Web Service part from the internet. Now you need to extend some portion of the WSDL file. Open the first link in your browser, it will display 2 conversions for you:
  • CelsiusToFahrenheit
  • FahrenheitToCelsius
Select anyone of them, and you will see following screen:

AndWeb10.jpg

For CelsiusToFahrenheit:
  1. NAMESPACE = "http://tempuri.org/";
  2. METHOD_NAME = "CelsiusToFahrenheit";
For FahrenheitToCelsius:
  1. NAMESPACE = "http://tempuri.org/";
  2. METHOD_NAME = " FahrenheitToCelsius ";
Step 6:

You need to understand some classes before proceeding to use a Web Service.
  1. SoapObject ( 

    A simple dynamic object that can be used to build SOAP calls without implementing KvmSerializable. Essentially, this is what goes inside the body of a SOAP envelope - it is the direct subelement of the body and all further sub elements. Instead of this class, custom classes can be used if they implement the KvmSerializable interface.

    Constructor:

    SoapObject (java.lang.String namespace, java.lang.String method) 
     
  2. SoapSerializationEnvelope

    This class extends the SoapEnvelope with Soap Serialization functionality.

    Constructor:
    SoapSerializationEnvelope (int version)

    Fields:
    Type
    Field
    Description
    boolean
    dotNet
    Set this variable to true for compatibility with what seems to be the default encoding for .Net-Services.
    Methods:
    Return Type
    Method Name
    Description
    void
    setOutputSoapObject(java.lang.Object soapObject)
    Assigns the object to the envelope as the outbound message for the soap call.

  3. HttpTransportSE (org.ksoap2.transport.HttpTransportSE)

    A J2SE based HttpTransport layer.

    Constructor:

    HttpTransportSE(java.lang.String url)

    Method:
    Return Type
    Method
    Description
    void
    call(java.lang.String SoapAction, SoapEnvelope envelope)
    set the desired soapAction header field
Step 7:

Open your "WebServiceDemo -> src -> WebServiceDemoActivity.java" file and enterr following code:

WebServiceDemoActivity.java
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class WebServiceDemoActivity extends Activity
{
    /** Called when the activity is first created. */
      private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
      private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
      private static String NAMESPACE = "http://tempuri.org/";
      private static String METHOD_NAME1 = "FahrenheitToCelsius";
      private static String METHOD_NAME2 = "CelsiusToFahrenheit";
      private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";

      Button btnFar,btnCel,btnClear;
      EditText txtFar,txtCel;
     
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        btnFar = (Button)findViewById(R.id.btnFar);
        btnCel = (Button)findViewById(R.id.btnCel);
        btnClear = (Button)findViewById(R.id.btnClear);
        txtFar = (EditText)findViewById(R.id.txtFar);
        txtCel = (EditText)findViewById(R.id.txtCel);
       
        btnFar.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        //Initialize soap request + add parameters
                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);       
                 
                  //Use this to add parameters
                  request.addProperty("Fahrenheit",txtFar.getText().toString());
                 
                  //Declare the version of the SOAP request
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                 
                  envelope.setOutputSoapObject(request);
                  envelope.dotNet = true;
                 
                  try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                       
                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION1, envelope);
                       
                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject)envelope.bodyIn;

                        if(result != null)
                        {
                              //Get the first property and change the label text
                              txtCel.setText(result.getProperty(0).toString());
                        }
                        else
                        {
                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  }
            });
       
        btnCel.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        //Initialize soap request + add parameters
                  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);       
                 
                  //Use this to add parameters
                  request.addProperty("Celsius",txtCel.getText().toString());
                 
                  //Declare the version of the SOAP request
                  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                 
                  envelope.setOutputSoapObject(request);
                  envelope.dotNet = true;
                 
                  try {
                        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                       
                        //this is the actual part that will call the webservice
                        androidHttpTransport.call(SOAP_ACTION2, envelope);
                       
                        // Get the SoapResult from the envelope body.
                        SoapObject result = (SoapObject)envelope.bodyIn;

                        if(result != null)
                        {
                              //Get the first property and change the label text
                              txtFar.setText(result.getProperty(0).toString());
                        }
                        else
                        {
                              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
                        }
                  } catch (Exception e) {
                        e.printStackTrace();
                  }
                  }
            });
       
        btnClear.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        txtCel.setText("");
                        txtFar.setText("");
                  }
            });
    }
}

Step 8:

Now, open your "WebServiceDemo -> android.manifest" file. Add the following line before the <application> tag:

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

This will allow the application to use the internet.

Step 9:

Run your application in the Android Cell. You will get the following outcome:

Note: In the emulator, we need to fix a proxy, so try the application in an Android Cell.

AndWeb11.jpg

Summary

In this brief tutorial, we learned about Web Services, SOAP envelopes, WSDL files, HTTP transport, and how to use the in an Android application.
 
Article Extensions
Contents added by pugazhendhi p on Jul 22, 2013
Contents added by Chintan Rathod on Nov 21, 2012
Hi Friends,

I searched for the actual error that has Eclipse problem for "NoClassFound".
I have fixed this by following.

------------------

Right click "project" -> Properties -> Java Build Path -> Order And Explort

------------------



Now, make sure that, you have "Checked" that external added "jar" file as you can see in the snap.
Make sure that order of that external jar file also same like displayed in snap.

Now, Run your project and enjoy.

Thanks & Regards
---------------------
Chintan Rathod
Contents added by Chintan Rathod on Oct 23, 2012
Following are steps for How to configure Proxy in "Run Configuration" when you are using emulator

Step 1:


Right click on "project" -> Run As -> Run Configuration



Proxy -> your internet access IP address
port    -> default 8080

Then click on "Apply".

Now, you can try to run web application in emulator, it will not give you any error regarding network connection.

Calling ASP.NET Webservice (ASMX) from an Android Application, the Simplest Way

Introduction

There are several tutorials already present over the internet on this topic. But while going through some of these tutorials, I realized that either they are too complicated for a layman or are not explained properly. This is an important aspect of Android apps as it can easily be used to use existing business logic in Android rather than rewriting them. Another important aspect of this application is that you can easily use a global database to store the data that can be shared by different phones as against common practice of using in built SQLLite database for Android.

Using the Code

First let us look at a simple webservice.
<%@ WebService language="C#" class="MyLocal" %>
using System;
using System.Web.Services;
using System.Xml.Serialization;
public class MyLocal {
    [WebMethod]
    public int Add(int a, int b) {
        return a + b;
    } 
}
While creating this webservice, it asks for a namespace and here the namespace is www.tempura.org (pretty much the default namespace which I have not changed!). You can open this service fromhttp://grasshoppernetwork.com/NewFile.asmx.
When you open this webservice in browser, you can see a window like in the figure below:
Android-asmx/figure-1.png
I have marked it to show how to get the namespace name. It will also show the list of methods, which you cannot test. So how to know the arguments and return type? Click on the method and see the figure below:
Android-asmx/Figure2-soap_structure.png
Now you know what function you are calling, its arguments, return type and namespace (and of course URL).
For calling this method you need ksoap library, which you can download from here.
Copy the downloaded zip file in any appropriate location. This is an external jar file which you need to include in your Android project.
Start an Android project and select Android API. Right click on the project node in the workspace, properties->java build path->libraries->Add external jar.
Browse and select your ksoap jar file.
All we have to do now is to write a method which can call the web service and return the result. Remember that Android gives you an exception if you try any socket operation from main activity thread. Therefore it is better to write a separate class and isolate soap related functions.
Let us now understand the logic of this class.
package my.MySOAPCallActivity.namespace; 
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://grasshoppernetwork.com/NewFile.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();
}
}
  • First SOAP_ACTION = namespace as seen in figure 1+function name;
  • OPERATION_NAME = name of the web method;
  • WSDL_TARGET_NAMESPACE = namespace of the webservice;
  • SOAP_ADDRESS = absolute URL of the webservice;
SOAP works on request response pair. So first you need to build a request object which can call the web service.
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,OPERATION_NAME);
Now the operation or the method that you intend to call has some arguments which you need to attach to the request object. This is done through PropertyInfo Instance pi. The important thing to notice here is that the name that you use in setName() method must be the exact name of the property that you have seen in the figure above and in setType(), the data type of the variable must be specified. UsingaddProperty(), add all the arguments.
Using setValue() method, set the value to the property.
PropertyInfo pi=new PropertyInfo(); 
pi.setName("a"); 
pi.setValue(a); 
pi.setType(Integer.class); 
request.addProperty(pi);
Create a serialized envelope which will be used to carry the parameters for SOAP body and call the method through HttpTransportSE method.
Now you are very much ready with techniques for calling web method and getting the result. For simplicity, we have made a simple Android GUI with two EditText and one Button.
See the main.xml code as below:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<EditText 
        android:id="@+id/editText1"
    android:layout_width="230dp"
    android:layout_height="wrap_content" >
    <requestFocus />
</EditText> 
<EditText
    android:id="@+id/editText2"
    android:layout_width="232dp"
    android:layout_height="wrap_content" />
<Button
    android:id="@+id/button1"
    android:layout_width="229dp"
    android:layout_height="wrap_content"
    android:text="@string/btnStr" />
</LinearLayout>
We want to call the method from button click event from activity class.
See the code below:
package my.MySOAPCallActivity.namespace;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class SimpleAsmxSOAPCallActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b1=(Button)findViewById(R.id.button1);
       final  AlertDialog ad=new AlertDialog.Builder(this).create();
         
        b1.setOnClickListener(new OnClickListener() { 
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
CallSoap cs=new CallSoap();

try
{
EditText ed1=(EditText)findViewById(R.id.editText1);
EditText ed2=(EditText)findViewById(R.id.editText2);
int a=Integer.parseInt(ed1.getText().toString());
int b=Integer.parseInt(ed2.getText().toString());

ad.setTitle("OUTPUT OF ADD of "+a+" and "+b);

String resp=cs.Call(a, b);
ad.setMessage(resp);
}catch(Exception ex)
{
ad.setTitle("Error!");
ad.setMessage(ex.toString());
}
ad.show(); }
});
    }
}
All you do now is get the values for a and b from EditTexts and pass the values to call method. Call method returns the result of the web method.
String resp=cs.Call(a, b);
ad.setMessage(resp);
Once you get this up and running, you are very much likely to get an error likeandroid.os.NetworkOnMainThreadException.
That is because Android does not permit you to run socket related operations from main thread as we had already discussed. So you need to run a thread or create a thread from where you can perform these operations. You can easily model the CallSoap class as one implementing runnable and get the stuff. But I wanted to have the calling part as a separate entity. So I just made a separate thread class for calling theCallSoap method. It gives a nice layered implementation so that the thread that is calling the function where SOAP related activities are performed is completely different.
But now the problem is your activity thread and the network thread are in multi-thread operation and chances are your main thread ends before getting the result from the SOAP operation. So I used a primitive way of waiting for the result to arrive and then using it.
The caller class.
public class Caller  extends Thread  
{
    public CallSoap cs;
    public int a,b; 

    public void run(){
        try{
            cs=new CallSoap();
            String resp=cs.Call(a, b);
            MySOAPCallActivity.rslt=resp;
        }catch(Exception ex)
        {MySOAPCallActivity.rslt=ex.toString();}    
    }
}
Modified OnClick method of the button in activity thread which calls SOAP through this simple caller class.
package my.MySOAPCallActivity.namespace;
import android.app.Activity;
import android.os.Bundle;
import android.app.AlertDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MySOAPCallActivity extends Activity {

public static String rslt="";    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button b1=(Button)findViewById(R.id.button1);
        final  AlertDialog ad=new AlertDialog.Builder(this).create();

        b1.setOnClickListener(new OnClickListener() {
  
            @Override public void onClick(View arg0) {
            // TODO Auto-generated method stub 

            try
            { 
                EditText ed1=(EditText)findViewById(R.id.editText1);
                EditText ed2=(EditText)findViewById(R.id.editText2); 
                int a=Integer.parseInt(ed1.getText().toString());
                int b=Integer.parseInt(ed2.getText().toString());
                rslt="START"; 
                Caller c=new Caller(); c.a=a;
                c.b=b; c.ad=ad;
                c.join(); c.start();
                while(rslt=="START") {
                    try {
                        Thread.sleep(10); 
                    }catch(Exception ex) {
                    }
                }
                ad.setTitle("RESULT OF ADD of "+a+" and "+b);
                ad.setMessage(rslt); 
            }catch(Exception ex) {
                ad.setTitle("Error!"); ad.setMessage(ex.toString());
            }
            ad.show(); 
        } });
    }
}
Finally you get the results as shown below:
Android-asmx/fig_4.png

Points of Interest

Though returning a Complex class like Employee or Person or anything like that is not as simple as the technique explained here. They need to have another serializable class. But if you love simplicity, you can return the values of the properties of the class embedded in a single string like "Name#Age#Phone".
Where ‘#’ is a delimiter. Remember that DataReader is not serializable. So your web method must convertDataReader to string format and after receiving the result, you can separate the fields with simplestring splitting method.
You can download the complete code from:
Calling WebService from Android source code
Update: How to Run the Service locally 
As against my understanding that it can not be done, our friend Motaz has suggested a nice tips and workaround. Including it in main article so that anyone reads finds the answer quickly.
you just need to set the ip address of the service to 10.0.2.2 and the URL of the service would be :
http://10.0.2.2/service/WSGetCustomerCountryWise.asmx[^]
where 
service is your web service alias name in the IIS server
WSGetCustomerCountryWise is the name of the web service 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

2013年11月20日星期三

关于Android Studio加载第三方jar包无法编译的问题解决


Android Studio刚发布,相信很多朋友和我一样,开始尝试用其开发项目,但新东西总会遇到这样或那样的问题,其中最令我头的就是引入第三方的jar包无法编译的问题,因为是新东西,相关的信息都比较少,解决问题令我花费了相当长的时间,为了避免各位同仁再走弯路,在此将解决步骤列出来。

1、将jar包放入项目里的libs文件夹中。

2、在project选中jar包点击右键"Add as library"。

3、这两步是网上比较容易找到的,但此时项目仍然是无法正常编译的,会出现:

Gradle:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':ABetone:compileDebug'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.


Could not execute build using Gradle distribution 'http://services.gradle.org/distributions/gradle-1.6-bin.zip'.
  这时需要在项目的build.gradle文件里的dependencies节加入

dependencies {
    compile files('libs/android-support-v4.jar')
    compile files('libs/xxxx.jar')
}
4、此时项目正常编译并运行了,但当你的代码中真正创建了引用jar里的类实例时,有可能系统会抛出异常NoClassDefFoundError,这个时候可以按以下步骤操作:

进入命令提示符窗口。
定位到项目的根目录,即build.gradle所在的目录。
运行 "{android studio 安装目录}\sdk\tools\templates\gradle\wrapper\gradlew.bat" clean
重新编译运行项目
  通过以上操作,应该可以解决问题。PS:我的是Windows系统,Linux及Max系统gradlew命令的路径有可能不太一样。



希望以上能够帮助大家解决问题。