Consuming Web Services Using HTTP

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 25

CONSUMING WEB SERVICES

USING HTTP
• Creating web service application in android is not a difficult task. We can easily create a restful web service
application in android to authenticate or save information into the external database such as oracle, mysql,
postgre sql, sql server using other application developed in java, .net, php etc languages. That is what we are
going to do.
• Android Restful Web Service
• Before developing web services application, you must have basic knowledge of SOAP and Restful web services.
Resfull Webservices.
RESTful web services are loosely coupled, lightweight web services that are particularly well suited for creating
APIs for clients spread out across the internet. In the REST architecture style, clients and servers exchange
representations of resources by using a standardized interface and protocol.
SOAP Webservices.
• SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing web services.
• SOAP is a recommendation for communication between two applications.
• SOAP is XML based protocol. It is platform independent and language independent. By using SOAP, you will
be able to interact with other programming language applications.
ANDROID RESTFUL WEB SERVICE EXAMPLE

• Using Eclipse, create a new Android project and name it Networking.


Add the following statement in bold to the AndroidManifest.xml file:

<?xml version=”1.0” encoding=”utf-8”?>


<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”net.learn2develop.Networking”
android:versionCode=”1”
android:versionName=”1.0” >
<uses-sdk android:minSdkVersion=”14” />
<uses-permission android:name=”android.permission.INTERNET”/>
<application
android:icon=”@drawable/ic_launcher”
• Using Eclipse, create a new Android project and name it Networking.
Add the following statement in bold to the AndroidManifest.xml file:

<?xml version=”1.0” encoding=”utf-8”?>


<manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”net.learn2develop.Networking”
android:versionCode=”1”
android:versionName=”1.0” >
<uses-sdk android:minSdkVersion=”14” />
<uses-permission android:name=”android.permission.INTERNET”/>
<application
android:icon=”@drawable/ic_launcher”
<activity
android:label=”@string/app_name”
android:name=”.NetworkingActivity” >
<intent-filter >
<action android:name=”android.intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>
</manifest>
• Import the following packages in the NetworkingActivity.java file:
package net.learn2develop.Networking;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.util.Log;
public class NetworkingActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
• Define the OpenHttpConnection() method in the NetworkingActivity.java file:
public class NetworkingActivity extends Activity {
private InputStream OpenHttpConnection(String urlString) throws IOException
{
InputStream in = null;
int response = -1;

URL url = new URL(urlString);


URLConnection conn = url.openConnection();

if (!(conn instanceof HttpURLConnection))


throw new IOException(“Not an HTTP connection”);
try{
HttpURLConnection httpConn = throw new IOException(“Error connecting”);
(HttpURLConnection) conn;
}
httpConn.setAllowUserInteraction(false);
return in;
httpConn.setInstanceFollowRedirects(true);
}
httpConn.setRequestMethod(“GET”);
/** Called when the activity is first created. */
httpConn.connect();
@Override
response = httpConn.getResponseCode();
public void onCreate(Bundle savedInstanceState) {
if (response == HttpURLConnection.HTTP_OK) {
super.onCreate(savedInstanceState);
in = httpConn.getInputStream();
setContentView(R.layout.main);
}
}
}
}
catch (Exception ex)
{
Log.d(“Networking”, ex.getLocalizedMessage());
HOW IT WORKS

• Because you are using the HTTP protocol to connect to the web, your application needs the INTERNET
permission; hence, the fi rst thing you did was add the permission in the AndroidManifest.xml fi le. You then
defi ned the OpenHttpConnection() method, which takes a URL string and returns an InputStream object.
Using an InputStream object, you can download the data by reading bytes from the stream object. In this
method, you made use of the HttpURLConnection object to open an HTTP connection with a remote URL. You
set all the various properties of the connection, such as the request method, and so on:
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod(“GET”);
• After trying to establish a connection with the server, the HTTP response code is returned. If the connection is
established (via the response code HTTP_OK), then you proceed to get an InputStream object from the
connection:
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
ACESSING WEB SERVICES

• 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:
Example acessing or calling webservice
EXAMPLE

<?xml version="1.0" encoding="utf-8"?>           android:layout_width="match_parent"  
<LinearLayout xmlns:android="http://         android:layout_height="wrap_content" >  
schemas.android.com/apk/res/android"  
        <requestFocus />  
    android:layout_width="match_parent"  
    </EditText>  
    android:layout_height="match_parent"  
    <TextView  
    android:orientation="vertical" >  
        android:id="@+id/textView2"  
    <TextView  
        android:layout_width="wrap_content"  
        android:id="@+id/textView1"  
        android:layout_height="wrap_content"  
        android:layout_width="wrap_content"  
        android:text="Celsius"  
        android:layout_height="wrap_content"  
        android:textAppearance="?android:attr/
        android:text="Fahrenheit"   textAppearanceLarge" />  
        android:textAppearance="?android:attr/     <EditText  
textAppearanceLarge" />  
        android:id="@+id/txtCel"  
    <EditText  
        android:layout_width="match_parent"  
        android:id="@+id/txtFar"  
      
  android:layout_height="wrap_content" />               android:text="Convert To Fahrenheit" /
>  
    <LinearLayout  
    </LinearLayout>  
        android:id="@+id/linearLayout1"  
    <Button  
        android:layout_width="match_parent"  
        android:id="@+id/btnClear"  
        android:layout_height="wrap_content" >  
        android:layout_width="match_parent"  
        <Button  
        android:layout_height="wrap_content"  
            android:id="@+id/btnFar"  
        android:text="Clear" />  
            android:layout_width="wrap_content"  
</LinearLayout>  
            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"  
THIS WILL APEAR ON YOUR
AMULATOR SCREEN
• 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 CelsiusToFahrenheitSOAP_ACTION = "http://tempuri.org/CelsiusToFahrenheit";
• NAMESPACE = "http://tempuri.org/";
• METHOD_NAME = "CelsiusToFahrenheit";
• URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
• For FahrenheitToCelsius
• SOAP_ACTION = "http://tempuri.org/FahrenheitToCelsius";
• NAMESPACE = "http://tempuri.org/";
• METHOD_NAME = " FahrenheitToCelsius ";
• URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
• You need to understand some classes before proceeding to use a Web Service.
• You need to understand some classes before proceeding to use a Web Service.
• 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.
• ConstructorSoapObject (java.lang.String namespace, java.lang.String method)
• SoapSerializationEnvelopeThis class extends the SoapEnvelope with Soap Serialization functionality.
• ConstructorSoapSerializationEnvelope (int version)
Fields

Type Field Description


Set this variable to true for
compatibility with what seems to
boolean dotNet
be the default encoding for .Net-
Services.

Methods

Return Type Method Name Description

setOutputSoapObject(ja Assigns the object to the


void va.lang.Object soapObjec envelope as the outbound
t) message for the soap call.
• HttpTransportSE (org.ksoap2.transport.HttpTransportSE)A J2SE based HTTP transport layer.
• Constructor
HttpTransportSE(java.lang.String url)
Method

Return Type Method Description

call(java.lang.String Soap
set the desired
void Action,
soapAction header field
SoapEnvelope envelope)

Open your "WebServiceDemo -> src ->


WebServiceDemoActivity.java" file and enterr following
code.
WEBSERVICEDEMOACTIVITY.JAVA

import org.ksoap2.SoapEnvelope;       private static String METHOD_NAME1 = "FahrenheitToCelsius";
import org.ksoap2.serialization.SoapObject;       private static String METHOD_NAME2 = "CelsiusToFahrenheit";
import org.ksoap2.serialization.SoapSerializationEnvelope;       private static String URL = "http://www.w3schools.com/
webservices/tempconvert.asmx?WSDL";  
import org.ksoap2.transport.HttpTransportSE;  
    Button btnFar,btnCel,btnClear;  
import android.app.Activity;  
    EditText txtFar,txtCel;  
import android.os.Bundle;  
    @Override  
import android.view.View;  
    public void onCreate(Bundle savedInstanceState)  
import android.widget.Button;  
    {  
import android.widget.EditText;  
        super.onCreate(savedInstanceState);  
import android.widget.Toast;  
        setContentView(R.layout.main);  
public class WebServiceDemoActivity extends Activity  
        btnFar = (Button)findViewById(R.id.btnFar);  
{  
        btnCel = (Button)findViewById(R.id.btnCel);  
    /** Called when the activity is first created. */  
        btnClear = (Button)findViewById(R.id.btnClear);  
    private static String SOAP_ACTION1 = "http://tempuri.org/
FahrenheitToCelsius";           txtFar = (EditText)findViewById(R.id.txtFar);  
    private static String SOAP_ACTION2 = "http://tempuri.org/         txtCel = (EditText)findViewById(R.id.txtCel);  
CelsiusToFahrenheit";  
        btnFar.setOnClickListener(new View.OnClickListener()  
    private static String NAMESPACE = "http://tempuri.org/";  
      
  {                           // Get the SoapResult from the envel
ope body.  
            @Override  
                        SoapObject result = (SoapObject)enve
            public void onClick(View v)  
lope.bodyIn;  
            {  
                        if(result != null)  
                //Initialize soap request + add parameters  
                        {  
                SoapObject request = new SoapObject(NAMESPAC
                              //
E, METHOD_NAME1);  
Get the first property and change the label text  
                //Use this to add parameters  
                              txtCel.setText(result.getPrope
                request.addProperty("Fahrenheit",txtFar.getT rty(0).toString());  
ext().toString());  
                        }  
                //Declare the version of the SOAP request  
                        else  
               
                        {  
SoapSerializationEnvelope envelope = new SoapSerializationEn
velope(SoapEnvelope.VER11);                                 Toast.makeText(getApplicationC
ontext(), "No Response",Toast.LENGTH_LONG).show();  
                envelope.setOutputSoapObject(request);  
                        }  
                envelope.dotNet = true;  
                  } catch (Exception e) {  
                try {  
                        e.printStackTrace();  
                        HttpTransportSE androidHttpTransport
 = new HttpTransportSE(URL);                     }  
                        //                   }  
this is the actual part that will call the webservice  
  
                        androidHttpTransport.call(SOAP_ACTIO
N1, envelope);  
                        {  
            });                                 //
Get the first property and change the label text  
        btnCel.setOnClickListener(new View.OnClickListener()  
                              txtFar.setText(result.getProperty(0).toStr
        {  
ing());  
            @Override  
                        }  
            public void onClick(View v)  
                        else  
            {  
                        {  
                //Initialize soap request + add parameters  
                              Toast.makeText(getApplicationContext(), "N
                o Response",Toast.LENGTH_LONG).show();  
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);         
                        }  
                //Use this to add parameters  
                  } catch (Exception e) {  
               
                        e.printStackTrace();  
request.addProperty("Celsius",txtCel.getText().toString());  
                  }  
                //Declare the version of the SOAP request  
                  }  
               
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapE             });  
nvelope.VER11);  
        btnClear.setOnClickListener(new View.OnClickListener()  
                envelope.setOutputSoapObject(request);  
        {  
                envelope.dotNet = true;  
            @Override  
                try {  
            public void onClick(View v)  
                        HttpTransportSE androidHttpTransport = new HttpT
            {
ransportSE(URL);  
                txtCel.setText("");  
                        //
this is the actual part that will call the webservice                   txtFar.setText("");  
                        androidHttpTransport.call(SOAP_ACTION2, envelope             }  
);           });  
                        // Get the SoapResult from the envelope body.       }  
                        SoapObject result = (SoapObject)envelope.bodyIn; }  
  
                        if(result != null)  
• 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.
• Run your application in the Android Cell. You will get the following outcome:
OUTCOME

You might also like