Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

Android Web Service


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 Tutorial

Before developing web services application, you must have basic knowledge of SOAP and Restful web services. That is why, we are going to discuss basic points about web services such as what is web service and brief information about SOAP and Restful web services.

What is Web Service?

A web service is a standard for exchanging information between different types of applications irrespective of language and platform. For example, an android application can interact with java or .net application using web services.

Android Restful Web Service Example

File: activity_main.xml
  1. <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
  2.     xmlns:tools=“http://schemas.android.com/tools”
  3.     android:layout_width=“match_parent”
  4.     android:layout_height=“match_parent”
  5.     android:paddingBottom=“@dimen/activity_vertical_margin”
  6.     android:paddingLeft=“@dimen/activity_horizontal_margin”
  7.     android:paddingRight=“@dimen/activity_horizontal_margin”
  8.     android:paddingTop=“@dimen/activity_vertical_margin”
  9.     tools:context=“.MainActivity” >
  10.     <EditText
  11.         android:id=“@+id/editText1”
  12.         android:layout_width=“wrap_content”
  13.         android:layout_height=“wrap_content”
  14.         android:layout_alignParentTop=“true”
  15.         android:layout_centerHorizontal=“true”
  16.         android:hint=“Username”
  17.         android:ems=“10” >
  18.         <requestFocus />
  19.     </EditText>
  20.     <EditText
  21.         android:id=“@+id/editText2”
  22.         android:layout_width=“wrap_content”
  23.         android:layout_height=“wrap_content”
  24.         android:layout_alignLeft=“@+id/editText1”
  25.         android:layout_below=“@+id/editText1”
  26.         android:layout_marginTop=“67dp”
  27.         android:ems=“10”
  28.         android:hint=“Password”
  29.         android:inputType=“textPassword” />
  30.     <Button
  31.         android:id=“@+id/button2”
  32.         android:layout_width=“wrap_content”
  33.         android:layout_height=“wrap_content”
  34.         android:layout_alignParentBottom=“true”
  35.         android:layout_marginBottom=“24dp”
  36.         android:layout_toRightOf=“@+id/button1”
  37.         android:text=“New User” />
  38.     <ProgressBar
  39.         android:id=“@+id/progressBar1”
  40.         style=“?android:attr/progressBarStyleLarge”
  41.         android:layout_width=“wrap_content”
  42.         android:layout_height=“wrap_content”
  43.         android:layout_alignLeft=“@+id/button1”
  44.         android:layout_below=“@+id/editText2”
  45.         android:layout_marginTop=“22dp” />
  46.     <Button
  47.         android:id=“@+id/button1”
  48.         android:layout_width=“wrap_content”
  49.         android:layout_height=“wrap_content”
  50.         android:layout_alignLeft=“@+id/editText2”
  51.         android:layout_below=“@+id/progressBar1”
  52.         android:layout_marginLeft=“22dp”
  53.         android:text=“Login” />
  54. </RelativeLayout>
File: activity_register_user.xml
  1. <RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
  2.     android:layout_width=“fill_parent”
  3.     android:layout_height=“fill_parent” >
  4.     <EditText
  5.         android:id=“@+id/editText1”
  6.         android:layout_width=“wrap_content”
  7.         android:layout_height=“wrap_content”
  8.         android:layout_alignParentTop=“true”
  9.         android:layout_centerHorizontal=“true”
  10.         android:layout_marginTop=“15dp”
  11.         android:ems=“10”
  12.         android:hint=“Enter UserName” />
  13.     <EditText
  14.         android:id=“@+id/editText2”
  15.         android:layout_width=“wrap_content”
  16.         android:layout_height=“wrap_content”
  17.         android:layout_alignLeft=“@+id/editText1”
  18.         android:layout_below=“@+id/editText1”
  19.         android:layout_marginTop=“50dp”
  20.         android:ems=“10”
  21.         android:hint=“Enter Password”
  22.         android:inputType=“textPassword” />
  23.     <Button
  24.         android:id=“@+id/button1”
  25.         android:layout_width=“wrap_content”
  26.         android:layout_height=“wrap_content”
  27.         android:layout_alignParentBottom=“true”
  28.         android:layout_centerHorizontal=“true”
  29.         android:text=“Resister” />
  30.     <ProgressBar
  31.         android:id=“@+id/progressBar1”
  32.         style=“?android:attr/progressBarStyleLarge”
  33.         android:layout_width=“wrap_content”
  34.         android:layout_height=“wrap_content”
  35.         android:layout_alignLeft=“@+id/button1”
  36.         android:layout_below=“@+id/editText2”
  37.         android:layout_marginTop=“87dp” />
  38. </RelativeLayout>

MainActivity class

File: MainActivity.java
  1. package com.example.newrestapi;
  2. import java.io.BufferedReader;
  3. import java.io.InputStream;
  4. import java.io.InputStreamReader;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. import org.apache.http.HttpEntity;
  8. import org.apache.http.HttpResponse;
  9. import org.apache.http.NameValuePair;
  10. import org.apache.http.client.HttpClient;
  11. import org.apache.http.client.entity.UrlEncodedFormEntity;
  12. import org.apache.http.client.methods.HttpPost;
  13. import org.apache.http.impl.client.DefaultHttpClient;
  14. import org.apache.http.message.BasicNameValuePair;
  15. import android.os.AsyncTask;
  16. import android.os.Bundle;
  17. import android.app.Activity;
  18. import android.content.Intent;
  19. import android.view.View;
  20. import android.view.View.OnClickListener;
  21. import android.widget.Button;
  22. import android.widget.EditText;
  23. import android.widget.ProgressBar;
  24. import android.widget.Toast;
  25. public class MainActivity extends Activity {
  26.     EditText password,userName;
  27.     Button login,resister;
  28.     ProgressBar progressBar;
  29.     protected void onCreate(Bundle savedInstanceState) {
  30.         super.onCreate(savedInstanceState);
  31.         setContentView(R.layout.activity_main);
  32.         password=(EditText) findViewById(R.id.editText2);
  33.         userName=(EditText) findViewById(R.id.editText1);
  34.         login=(Button) findViewById(R.id.button1);
  35.         resister=(Button) findViewById(R.id.button2);
  36.         //progess_msz.setVisibility(View.GONE);
  37.         progressBar=(ProgressBar) findViewById(R.id.progressBar1);
  38.         progressBar.setVisibility(View.GONE);
  39.         resister.setOnClickListener(new OnClickListener() {
  40.             @Override
  41.             public void onClick(View arg0) {
  42.                 // TODO Auto-generated method stub
  43.                 Intent  intent=new Intent(MainActivity.this,ResisterUser.class);
  44.                 startActivity(intent);
  45.             }
  46.         });
  47.         login.setOnClickListener(new OnClickListener() {
  48.             public void onClick(View v) {
  49.                 progressBar.setVisibility(View.VISIBLE);
  50.                 String s1=userName.getText().toString();
  51.                 String s2=password.getText().toString();
  52.                 new ExecuteTask().execute(s1,s2);
  53.             }
  54.         });
  55.     }
  56.      class ExecuteTask extends AsyncTask<String, Integer, String>
  57.         {
  58.             @Override
  59.             protected String doInBackground(String… params) {
  60.                 String res=PostData(params);
  61.                 return res;
  62.             }
  63.             @Override
  64.             protected void onPostExecute(String result) {
  65.             progressBar.setVisibility(View.GONE);
  66.             //progess_msz.setVisibility(View.GONE);
  67.             Toast.makeText(getApplicationContext(), result, 3000).show();
  68.             }
  69.         }
  70.     public String PostData(String[] valuse) {
  71.         String s=“”;
  72.         try
  73.         {
  74.         HttpClient httpClient=new DefaultHttpClient();
  75.         HttpPost httpPost=new HttpPost(“http://10.0.0.8:7777/HttpPostServlet/servlet/Login”);
  76.         List<NameValuePair> list=new ArrayList<NameValuePair>();
  77.         list.add(new BasicNameValuePair(“name”, valuse[0]));
  78.         list.add(new BasicNameValuePair(“pass”,valuse[1]));
  79.         httpPost.setEntity(new UrlEncodedFormEntity(list));
  80.         HttpResponse httpResponse=  httpClient.execute(httpPost);
  81.         HttpEntity httpEntity=httpResponse.getEntity();
  82.         s= readResponse(httpResponse);
  83.         }
  84.         catch(Exception exception)  {}
  85.         return s;
  86.     }
  87.     public String readResponse(HttpResponse res) {
  88.         InputStream is=null;
  89.         String return_text=“”;
  90.         try {
  91.             is=res.getEntity().getContent();
  92.             BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
  93.             String line=“”;
  94.             StringBuffer sb=new StringBuffer();
  95.             while ((line=bufferedReader.readLine())!=null)
  96.             {
  97.             sb.append(line);
  98.             }
  99.             return_text=sb.toString();
  100.         } catch (Exception e)
  101.         {
  102.         }
  103.         return return_text;
  104.     }
  105. }

RegisterUser class

File: RegisterUser.java
  1. package com.example.newrestapi;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import org.apache.http.NameValuePair;
  5. import org.apache.http.client.HttpClient;
  6. import org.apache.http.client.entity.UrlEncodedFormEntity;
  7. import org.apache.http.client.methods.HttpPost;
  8. import org.apache.http.impl.client.DefaultHttpClient;
  9. import org.apache.http.message.BasicNameValuePair;
  10. import android.os.AsyncTask;
  11. import android.os.Bundle;
  12. import android.app.Activity;
  13. import android.view.View;
  14. import android.view.View.OnClickListener;
  15. import android.widget.Button;
  16. import android.widget.EditText;
  17. import android.widget.ProgressBar;
  18. public class ResisterUser extends Activity {
  19.      EditText userName,passwprd;
  20.        Button resister,login;
  21.        ProgressBar progressBar;
  22.         protected void onCreate(Bundle savedInstanceState) {
  23.             super.onCreate(savedInstanceState);
  24.             setContentView(R.layout.activity_resister_user);
  25.             userName=(EditText) findViewById(R.id.editText1);;
  26.             passwprd=(EditText) findViewById(R.id.editText2);
  27.             resister=(Button) findViewById(R.id.button1);
  28.             progressBar=(ProgressBar) findViewById(R.id.progressBar1);
  29.             progressBar.setVisibility(View.GONE);
  30.             resister.setOnClickListener(new OnClickListener() {
  31.                 @Override
  32.                 public void onClick(View v) {
  33.                     progressBar.setVisibility(View.VISIBLE);
  34.                     String s1=userName.getText().toString();
  35.                     String s2=passwprd.getText().toString();
  36.                     new ExecuteTask().execute(s1,s2);
  37.                 }
  38.             });
  39.         }
  40.         class ExecuteTask extends AsyncTask<String, Integer, String>
  41.         {
  42.             @Override
  43.             protected String doInBackground(String… params) {
  44.                 PostData(params);
  45.                 return null;
  46.             }
  47.             @Override
  48.             protected void onPostExecute(String result) {
  49.             progressBar.setVisibility(View.GONE);
  50.             }
  51.         }
  52.         public void PostData(String[] valuse) {
  53.             try
  54.             {
  55.             HttpClient httpClient=new DefaultHttpClient();
  56.             HttpPost httpPost=new HttpPost(
  57.                                   “http://10.0.0.8:7777/HttpPostServlet/servlet/httpPostServlet”);
  58.             List<NameValuePair> list=new ArrayList<NameValuePair>();
  59.             list.add(new BasicNameValuePair(“name”, valuse[0]));
  60.             list.add(new BasicNameValuePair(“pass”,valuse[1]));
  61.             httpPost.setEntity(new UrlEncodedFormEntity(list));
  62.             httpClient.execute(httpPost);
  63.             }
  64.             catch(Exception e)
  65.             {
  66.                 System.out.println(e);
  67.             }
  68.         }
  69.         }

File: AndroidManifest.xml

You need to provide INTERNET permission in AndroidManifest.xml file.

  1. <?xml version=“1.0” encoding=“utf-8”?>
  2. <manifest xmlns:android=“http://schemas.android.com/apk/res/android”
  3.     package=“com.example.newrestapi”
  4.     android:versionCode=“1”
  5.     android:versionName=“1.0” >
  6.     <uses-sdk
  7.         android:minSdkVersion=“8”
  8.         android:targetSdkVersion=“17” />
  9.     <uses-permission android:name=“android.permission.INTERNET” />
  10.     <application
  11.         android:allowBackup=“true”
  12.         android:icon=“@drawable/ic_launcher”
  13.         android:label=“@string/app_name”
  14.         android:theme=“@style/AppTheme” >
  15.         <activity
  16.             android:name=“com.example.newrestapi.MainActivity”
  17.             android:label=“@string/app_name” >
  18.             <intent-filter>
  19.                 <action android:name=“android.intent.action.MAIN” />
  20.                 <category android:name=“android.intent.category.LAUNCHER” />
  21.             </intent-filter>
  22.         </activity>
  23.         <activity
  24.             android:name=“com.example.newrestapi.ResisterUser”
  25.             android:label=“@string/title_activity_resister_user” >
  26.         </activity>
  27.     </application>
  28. </manifest>

download this android example

Output:

webservice1

webservice2

Java Servlet Login and Register example using oracle database

Create table Kreationnext_user in the oracle database having three columns id, name and password. Id must be primary key and generated through SEQUENCE.

  1. CREATE TABLE  “Kreationnext_USER”
  2.    (    “ID” NUMBER,
  3.     “NAME” VARCHAR2(4000),
  4.     “PASSWORD” VARCHAR2(4000),
  5.      CONSTRAINT “Kreationnext_USER_PK” PRIMARY KEY (“ID”) ENABLE
  6.    )
  7. /

New create two servlet classes to login and register user.

Login Servlet class

File: Login.java
  1. package server;
  2. import java.io.IOException;
  3. import java.io.ObjectOutputStream;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import javax.servlet.ServletException;
  9. import javax.servlet.http.HttpServlet;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;
  12. public class Login extends HttpServlet {
  13.     public void doGet(HttpServletRequest request, HttpServletResponse response)
  14.             throws ServletException, IOException {
  15.          response.setContentType(“text/html”);
  16.             ObjectOutputStream out=new ObjectOutputStream(response.getOutputStream());
  17.             String n=request.getParameter(“name”);
  18.             String p=request.getParameter(“pass”);
  19.             System.out.println(n);
  20.             System.out.println(p);
  21.             if(validate(n, p)){
  22.                out.writeObject(“success”);
  23.             }
  24.             else{
  25.                out.writeObject(“Sorry username or password error”);
  26.             }
  27.             out.close();
  28.             }
  29.     public static boolean validate(String name,String pass){
  30.         boolean status=false;
  31.         try{
  32.             Class.forName(“oracle.jdbc.driver.OracleDriver”);
  33.             Connection con=DriverManager.getConnection(
  34.                       “jdbc:oracle:thin:@localhost:1521:xe”,“system”,“oracle”);
  35.         PreparedStatement ps=con.prepareStatement(
  36.         “select * from Kreationnext_user where name=? and password=?”);
  37.         ps.setString(1,name);
  38.         ps.setString(2,pass);
  39.         ResultSet rs=ps.executeQuery();
  40.         status=rs.next();
  41.         }catch(Exception e){System.out.println(e);}
  42.         return status;
  43.         }
  44.     public void doPost(HttpServletRequest request,HttpServletResponse response)
  45.     throws ServletException, IOException {
  46. doGet(request, response);
  47. }
  48. }

httpPostServlet Servlet class

File: httpPostServlet.java
  1. package server;
  2. import java.io.IOException;
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. public class httpPostServlet extends HttpServlet {
  11.      public void doGet(HttpServletRequest request,HttpServletResponse response)
  12.      throws ServletException, IOException {
  13.  response.setContentType(“text/html”);
  14. String recived_data=“”;
  15.  String s1=request.getParameter(“name”);
  16.  String s2=request.getParameter(“pass”);
  17.  System.out.println(s1);
  18.  System.out.println(s2);
  19.         try
  20.         {
  21.         Class.forName(“oracle.jdbc.driver.OracleDriver”);
  22.         Connection con=DriverManager.getConnection(
  23.                        “jdbc:oracle:thin:@localhost:1521:xe”,“system”,“oracle”);
  24.         PreparedStatement ps=con.prepareStatement(
  25.                       “insert into Kreationnext_user(name,password) values(?,?)”);
  26.         ps.setString(1, s1);
  27.         ps.setString(2,s2);
  28.         ps.executeUpdate();
  29.         con.close();
  30.         }
  31.         catch (Exception e) {
  32.             e.printStackTrace();
  33.         }
  34. }
  35. public void doPost(HttpServletRequest request,HttpServletResponse response)
  36.      throws ServletException, IOException {
  37.  doGet(request, response);
  38. }
  39. }

index.jsp

  1. <form action=“servlet/Login”>
  2. Name:<input type=“text” name=“name”/><br/>
  3. Password:<input type=“password” name=“pass”/><br/>
  4. <input type=“submit” value=“login”/>
  5. </form>

Comments

comments