[フレーム]

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 the SOAP Envelope:
Step 1
First, create a "New Android Project". Name it "WebServiceDemo" like below. Step 2 Now right-click on your "WebServiceDemo" project and select "New -> Folder" Now, give it a name it "lib". We need to add a SOAP library into this directory. 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"
  3. Now, click on "Add Jars" and select the ".jar" file from the "project -> lib" directory.
  4. Click on "Ok" to finish the procedure of adding the library to the Android application.
Step 4 Next, we need to create a layout of a screen. To do so, go to "WebServiceDemo -> res -> layout -> main.xml"
Open this XML file in editing mode, and place the below code. Main.xml
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:orientation="vertical">
  6. <TextView
  7. android:id="@+id/textView1"
  8. android:layout_width="wrap_content"
  9. android:layout_height="wrap_content"
  10. android:text="Fahrenheit"
  11. android:textAppearance="?android:attr/textAppearanceLarge"/>
  12. <EditText
  13. android:id="@+id/txtFar"
  14. android:layout_width="match_parent"
  15. android:layout_height="wrap_content">
  16. <requestFocus/>
  17. </EditText>
  18. <TextView
  19. android:id="@+id/textView2"
  20. android:layout_width="wrap_content"
  21. android:layout_height="wrap_content"
  22. android:text="Celsius"
  23. android:textAppearance="?android:attr/textAppearanceLarge"/>
  24. <EditText
  25. android:id="@+id/txtCel"
  26. android:layout_width="match_parent"
  27. android:layout_height="wrap_content"/>
  28. <LinearLayout
  29. android:id="@+id/linearLayout1"
  30. android:layout_width="match_parent"
  31. android:layout_height="wrap_content">
  32. <Button
  33. android:id="@+id/btnFar"
  34. android:layout_width="wrap_content"
  35. android:layout_height="wrap_content"
  36. android:layout_weight="0.5"
  37. android:text="Convert To Celsius"/>
  38. <Button
  39. android:id="@+id/btnCel"
  40. android:layout_width="wrap_content"
  41. android:layout_height="wrap_content"
  42. android:layout_weight="0.5"
  43. android:text="Convert To Fahrenheit"/>
  44. </LinearLayout>
  45. <Button
  46. android:id="@+id/btnClear"
  47. android:layout_width="match_parent"
  48. android:layout_height="wrap_content"
  49. android:text="Clear"/>
  50. </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:
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 HTTP transport 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
  1. import org.ksoap2.SoapEnvelope;
  2. import org.ksoap2.serialization.SoapObject;
  3. import org.ksoap2.serialization.SoapSerializationEnvelope;
  4. import org.ksoap2.transport.HttpTransportSE;
  5. import android.app.Activity;
  6. import android.os.Bundle;
  7. import android.view.View;
  8. import android.widget.Button;
  9. import android.widget.EditText;
  10. import android.widget.Toast;
  11. publicclass WebServiceDemoActivity extends Activity
  12. {
  13. /** Called when the activity is first created. */
  14. privatestatic String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
  15. privatestatic String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
  16. privatestatic String NAMESPACE = "http://tempuri.org/";
  17. privatestatic String METHOD_NAME1 = "FahrenheitToCelsius";
  18. privatestatic String METHOD_NAME2 = "CelsiusToFahrenheit";
  19. privatestatic String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
  20. Button btnFar,btnCel,btnClear;
  21. EditText txtFar,txtCel;
  22. @Override
  23. publicvoid onCreate(Bundle savedInstanceState)
  24. {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.main);
  27. btnFar = (Button)findViewById(R.id.btnFar);
  28. btnCel = (Button)findViewById(R.id.btnCel);
  29. btnClear = (Button)findViewById(R.id.btnClear);
  30. txtFar = (EditText)findViewById(R.id.txtFar);
  31. txtCel = (EditText)findViewById(R.id.txtCel);
  32. btnFar.setOnClickListener(new View.OnClickListener()
  33. {
  34. @Override
  35. publicvoid onClick(View v)
  36. {
  37. //Initialize soap request + add parameters
  38. SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
  39. //Use this to add parameters
  40. request.addProperty("Fahrenheit",txtFar.getText().toString());
  41. //Declare the version of the SOAP request
  42. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  43. envelope.setOutputSoapObject(request);
  44. envelope.dotNet = true;
  45. try {
  46. HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
  47. //this is the actual part that will call the webservice
  48. androidHttpTransport.call(SOAP_ACTION1, envelope);
  49. // Get the SoapResult from the envelope body.
  50. SoapObject result = (SoapObject)envelope.bodyIn;
  51. if(result != null)
  52. {
  53. //Get the first property and change the label text
  54. txtCel.setText(result.getProperty(0).toString());
  55. }
  56. else
  57. {
  58. Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
  59. }
  60. } catch (Exception e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. });
  65. btnCel.setOnClickListener(new View.OnClickListener()
  66. {
  67. @Override
  68. publicvoid onClick(View v)
  69. {
  70. //Initialize soap request + add parameters
  71. SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);
  72. //Use this to add parameters
  73. request.addProperty("Celsius",txtCel.getText().toString());
  74. //Declare the version of the SOAP request
  75. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  76. envelope.setOutputSoapObject(request);
  77. envelope.dotNet = true;
  78. try {
  79. HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
  80. //this is the actual part that will call the webservice
  81. androidHttpTransport.call(SOAP_ACTION2, envelope);
  82. // Get the SoapResult from the envelope body.
  83. SoapObject result = (SoapObject)envelope.bodyIn;
  84. if(result != null)
  85. {
  86. //Get the first property and change the label text
  87. txtFar.setText(result.getProperty(0).toString());
  88. }
  89. else
  90. {
  91. Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
  92. }
  93. } catch (Exception e) {
  94. e.printStackTrace();
  95. }
  96. }
  97. });
  98. btnClear.setOnClickListener(new View.OnClickListener()
  99. {
  100. @Override
  101. publicvoid onClick(View v)
  102. {
  103. txtCel.setText("");
  104. txtFar.setText("");
  105. }
  106. });
  107. }
  108. }
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 them in an Android application.

People also reading
Membership not found

AltStyle によって変換されたページ (->オリジナル) /