Thu. Apr 25th, 2024

Understanding of Web services

Web services are open standard (XML, SOAP, HTTP etc.) based Web applications that interact with other web applications for the purpose of exchanging data. Web Services can convert your existing applications into Web-applications. Different books and different organizations provide different definitions to Web Services. Some of them are listed here.

A web service is any piece of software that makes itself available over the internet and uses a standardized XML messaging system. XML is used to encode all communications to a web service. For example, a client invokes a web service by sending an XML message, then waits for a corresponding XML response. As all communication is in XML, web services are not tied to any one operating system or programming language–Java can talk with Perl; Windows applications can talk with Unix applications.

Web services are self-contained, modular, distributed, dynamic applications that can be described, published, located, or invoked over the network to create products, processes, and supply chains. These applications can be local, distributed, or web-based. Web services are built on top of open standards such as TCP/IP, HTTP, Java, HTML, and XML.

Web services are XML-based information exchange systems that use the Internet for direct application-to-application interaction. These systems can include programs, objects, messages, or documents.

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards.

To summarize, a complete web service is, therefore, any service that:

  • Is available over the Internet or private (intranet) networks
  • Uses a standardized XML messaging system
  • Is not tied to any one operating system or programming language
  • Is self-describing via a common XML grammar
  • Is discoverable via a simple find mechanism

Components of Web Services

The basic web services platform is XML + HTTP. All the standard web services work using the following components

  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)

All these components have been discussed in the Web Services Architecture chapter.

How Does a Web Service Work?

A web service enables communication among various applications by using open standards such as HTML, XML, WSDL, and SOAP. A web service takes the help of:

  • XML to tag the data
  • SOAP to transfer a message
  • WSDL to describe the availability of service.

You can build a Java-based web service on Solaris that is accessible from your Visual Basic program that runs on Windows.You can also use C# to build new web services on Windows that can be invoked from your web application that is based on JavaServer Pages (JSP) and runs on Linux.

Example

Consider a simple account-management and order processing system. The accounting personnel use a client application built with Visual Basic or JSP to create new accounts and enter new customer orders.

The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts with a database to store information.The steps to perform this operation are as follows:

  • The client program bundles the account registration information into a SOAP message.
  • This SOAP message is sent to the web service as the body of an HTTP POST request.
  • The web service unpacks the SOAP request and converts it into a command that the application can understand.
  • The application processes the information as required and responds with a new unique account number for that customer.
  • Next, the web service packages the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
  • The client program unpacks the SOAP message to obtain the results of the account registration process.

Architecture

There are two ways to view the web service architecture:

The first is to examine the individual roles of each web service actor.The second is to examine the emerging web service protocol stack.

Web Service Roles

There are three major roles within the web service architecture:

Service Provider

This is the provider of the web service. The service provider implements the service and makes it available on the Internet.

Service Requestor

This is any consumer of the web service. The requestor utilizes an existing web service by opening a network connection and sending an XML request.

Service Registry

This is a logically centralized directory of services. The registry provides a central place where developers can publish new services or find existing ones. It therefore serves as a centralized clearing house for companies and their services.

Web Service Protocol Stack

A second option for viewing the web service architecture is to examine the emerging web service protocol stack. The stack is still evolving, but currently has four main layers.

Service Transport

This layer is responsible for transporting messages between applications. Currently, this layer includes Hyper Text Transport Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), File Transfer Protocol (FTP), and newer protocols such as Blocks Extensible Exchange Protocol (BEEP).

XML Messaging

This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this layer includes XML-RPC and SOAP.

Service Description

This layer is responsible for describing the public interface to a specific web service. Currently, service description is handled via the Web Service Description Language (WSDL).

Service Discovery

This layer is responsible for centralizing services into a common registry and providing easy publish/find functionality. Currently, service discovery is handled via Universal Description, Discovery, and Integration (UDDI).

As web services evolve, additional layers may be added and additional technologies may be added to each layer.

The next chapter explains the components of web services.

Few Words about Service Transport

The bottom of the web service protocol stack is service transport. This layer is responsible for actually transporting XML messages between two computers.

Hyper Text Transfer Protocol (HTTP)

Currently, HTTP is the most popular option for service transport. HTTP is simple, stable, and widely deployed. Furthermore, most firewalls allow HTTP traffic. This allows XML-RPC or SOAP messages to masquerade as HTTP messages. This is good if you want to integrate remote applications, but it does raise a number of security concerns.

Blocks Extensible Exchange Protocol (BEEP)

This is a promising alternative to HTTP. BEEP is a new Internet Engineering Task Force (IETF) framework for building new protocols. BEEP is layered directly on TCP and includes a number of built-in features, including an initial handshake protocol, authentication, security, and error handling. Using BEEP, one can create new protocols for a variety of applications, including instant messaging, file transfer, content syndication, and network management.

SOAP is not tied to any specific transport protocol. In fact, you can use SOAP via HTTP, SMTP, or FTP. One promising idea is therefore to use SOAP over BEEP.

Json

  • JSON stands for JavaScript Object Notation
  • JSON is a lightweight data-interchange format
  • JSON is language independent *
  • JSON is “self-describing” and easy to understand
  • Much Like XML Because
  • Both JSON and XML are “self describing” (human readable)
  • Both JSON and XML are hierarchical (values within values)
  • Both JSON and XML can be parsed and used by lots of programming languages
  • Both JSON and XML can be fetched with an XMLHttpRequest
  • Much Unlike XML Because
  • JSON doesn’t use end tag
  • JSON is shorter
  • JSON is quicker to read and write
  • JSON can use arrays

The biggest difference is:

XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.

Why JSON?

For AJAX applications, JSON is faster and easier than XML:

Using XML

  • Fetch an XML document
  • Use the XML DOM to loop through the document
  • Extract values and store in variables

Using JSON

  • Fetch a JSON string
  • JSON.Parse the JSON string
  • JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

  • Data is in name/value pairs
  • Data is separated by commas
  • Curly braces hold objects
  • Square brackets hold arrays
  • JSON Data – A Name and a Value
  • JSON data is written as name/value pairs.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

Example

“firstName”:”John”

JSON names require double quotes. JavaScript names don’t.

JSON Values

JSON values can be:

A number (integer or floating point)

A string (in double quotes)

A Boolean (true or false)

An array (in square brackets)

An object (in curly braces)

null

JSON Objects

JSON objects are written inside curly braces.

Just like JavaScript, JSON objects can contain multiple name/values pairs:

Example

{“firstName”:”John”, “lastName”:”Doe”}

JSON Arrays

JSON arrays are written inside square brackets.

Just like JavaScript, a JSON array can contain multiple objects:

Example

“employees”:[

    {“firstName”:”John”, “lastName”:”Doe”},

    {“firstName”:”Anna”, “lastName”:”Smith”},

    {“firstName”:”Peter”,”lastName”:”Jones”}

]

In the example above, the object “employees” is an array containing three objects. Each object is a record of a person (with a first name and a last name).

Async Task

 Purpose of the AsyncTask class

The AsyncTask class allows to run instructions in the background and to synchronize again with the main thread. It also reporting progress of the running tasks. AsyncTasks should be used for short background operations which need to update the user interface. .

Using the AsyncTask class

To use AsyncTask you must subclass it. AsyncTask uses generics and varargs. The parameters are the following AsyncTask <TypeOfVarArgParams , ProgressValue , ResultValue>.

An AsyncTask is started via the execute() method. This execute() method calls the doInBackground() and the onPostExecute() method.

TypeOfVarArgParams is passed into the doInBackground() method as input. ProgressValue is used for progress information and ResultValue must be returned from doInBackground() method. This parameter is passed to onPostExecute() as a parameter.

The doInBackground() method contains the coding instruction which should be performed in a background thread. This method runs automatically in a separate Thread.

The onPostExecute() method synchronizes itself again with the user interface thread and allows it to be updated. This method is called by the framework once the doInBackground() method finishes.

Parallel execution of several AsyncTasks

Android executes AsyncTask tasks before Android 1.6 and again as of Android 3.0 in sequence by default. You can tell Android to run it in parallel with the usage of the executeOnExecutor() method specifying AsyncTask.THREAD_POOL_EXECUTOR as first parameter.

The following code snippet demonstrates that.

// ImageLoader extends AsyncTask

ImageLoader imageLoader = new ImageLoader( imageView );

// Execute in parallel

imageLoader.executeOnExecutor( AsyncTask.THREAD_POOL_EXECUTOR, “http://url.com/image.png” );

[NOTE} The AsyncTask does not handle configuration changes automatically, i.e. if the activity is recreated. The programmer has to handle that in his coding. A common solution to this is to declare the AsyncTask in a retained headless fragment.

Example: AsyncTask

The following code demonstrates how to use the AsyncTask class to download the content of a webpage.

Create a new Android project called de.vogella.android.asynctask with an activity called ReadWebpageAsyncTask. Add the android.permission.INTERNET permission to your AndroidManifest.xml file.

Sending Data to server

Sending data to server using Async task.

Retrieving Data from Server

Retrieving data to server using Async task.

activity_main.xml

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

    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Welcome"
        android:gravity="center"/>


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="email"
            android:inputType="textEmailAddress"
            android:id="@+id/email"
            />


        <EditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="password"
            android:inputType="textPassword"
            android:id="@+id/pass"/>


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



</LinearLayout>

MainActivity.java

package com.androidina.reg;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    EditText email,password;
    Button bt;
    String  upass, uemail;
    String respone="";
    JSONObject jsonoBject=null;
        @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        email=  findViewById(R.id.email);
        password=  findViewById(R.id.pass);

        bt=(Button)findViewById(R.id.reg);



        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                upass = password.getText().toString().trim();
                uemail = email.getText().toString().trim();

                JSONObject samreg=new JSONObject();
                try {

                    samreg.put("email", uemail);
                    samreg.put("password", upass);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                Reg re = new Reg();
                re.execute(samreg.toString());
                Log.e("Json Values", samreg.toString());
            }
        });
    }

    public class Reg extends AsyncTask<String,String,String> {
        /*String url = "http://official-joke-api.appspot.com/random_joke";*/
        /*String url="https://reqres.in/api/users?page=2"*/ ;
        String url="https://reqres.in/api/register";

        @Override
        protected String doInBackground(String... params) {
            Log.i("json", "" + params[0]);
            jsonoBject = JsonFunction.getJsonFromUrl(url);
            Log.i("json", "" + jsonoBject);
            return String.valueOf(jsonoBject);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject jsonObject = new JSONObject(jsonoBject.toString());
                respone = jsonObject.getString(s);



                    String status = jsonObject.getString("page");
                    Log.i("json",status);
                    Toast.makeText(getApplicationContext(), "" + status, Toast.LENGTH_LONG).show();






            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}

JsonFunction.java

package com.androidina.reg;

import android.util.Log;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class JsonFunction {

    public static JSONObject getJsonFromUrl(String url)
    {
        JSONObject jsonObject = null;

        try {

            URL jsonUrl=new URL(url);
            HttpURLConnection connection= (HttpURLConnection) jsonUrl.openConnection();
            InputStream is=new BufferedInputStream(connection.getInputStream());
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
            StringBuffer sb=new StringBuffer();
            String line;
            while ((line=bufferedReader.readLine())!=null)
            {
                sb.append(line+"\n");
            }
            is.close();
            Log.i("sb",sb.toString());
            jsonObject=new JSONObject(sb.toString());

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    public static JSONObject getJsonFromUrlparam(String url, String para)
    {
        JSONObject jsonObject = null;

        try {

            URL jsonUrl=new URL(url);
            HttpURLConnection connection= (HttpURLConnection) jsonUrl.openConnection();

           // connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(60000);
            connection.setRequestMethod("POST");
          //  connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
           // connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setUseCaches(false);
            connection.connect();

            //if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {

                OutputStream mOutPut = new BufferedOutputStream(connection.getOutputStream());
                mOutPut.write(para.getBytes());
                mOutPut.flush();

                InputStream is = new BufferedInputStream(connection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
                StringBuffer sb = new StringBuffer();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();

                Log.i("json", sb.toString());
                jsonObject = new JSONObject(sb.toString());
                Log.i("json", "" + jsonObject);
            //}
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    public static String getJsonUrlparamString(String url, String para)
    {
        StringBuffer sb = null;

        try {

            URL jsonUrl=new URL(url);
            HttpURLConnection connection= (HttpURLConnection) jsonUrl.openConnection();

            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setConnectTimeout(60000);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setUseCaches(false);
            connection.connect();


            OutputStream mOutPut = new BufferedOutputStream(connection.getOutputStream());
            mOutPut.write(para.getBytes());
            mOutPut.flush();

            InputStream is=new BufferedInputStream(connection.getInputStream());
            BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
            sb=new StringBuffer();
            String line;
            while ((line=bufferedReader.readLine())!=null)
            {
                sb.append(line+"\n");
            }
            is.close();

            Log.i("json",sb.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
}


Android_Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

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

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:usesCleartextTraffic="true"
        android:theme="@style/Theme.Reg"
        tools:targetApi="31">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *