AdSense

AdSense3

Friday, 6 November 2015

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.   
  11.     <EditText  
  12.         android:id="@+id/editText1"  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignParentTop="true"  
  16.         android:layout_centerHorizontal="true"  
  17.         android:hint="Username"  
  18.         android:ems="10" >  
  19.   
  20.     </EditText>  
  21.   
  22.     <EditText  
  23.         android:id="@+id/editText2"  
  24.         android:layout_width="wrap_content"  
  25.         android:layout_height="wrap_content"  
  26.         android:layout_alignLeft="@+id/editText1"  
  27.         android:layout_below="@+id/editText1"  
  28.         android:layout_marginTop="67dp"  
  29.         android:ems="10"  
  30.         android:hint="Password"  
  31.         android:inputType="textPassword" />  
  32.   
  33.     <Button  
  34.         android:id="@+id/button2"  
  35.         android:layout_width="wrap_content"  
  36.         android:layout_height="wrap_content"  
  37.         android:layout_alignParentBottom="true"  
  38.         android:layout_marginBottom="24dp"  
  39.         android:layout_toRightOf="@+id/button1"  
  40.         android:text="New User" />  
  41.   
  42.     <ProgressBar  
  43.         android:id="@+id/progressBar1"  
  44.         style="?android:attr/progressBarStyleLarge"  
  45.         android:layout_width="wrap_content"  
  46.         android:layout_height="wrap_content"  
  47.         android:layout_alignLeft="@+id/button1"  
  48.         android:layout_below="@+id/editText2"  
  49.         android:layout_marginTop="22dp" />  
  50.   
  51.     <Button  
  52.         android:id="@+id/button1"  
  53.         android:layout_width="wrap_content"  
  54.         android:layout_height="wrap_content"  
  55.         android:layout_alignLeft="@+id/editText2"  
  56.         android:layout_below="@+id/progressBar1"  
  57.         android:layout_marginLeft="22dp"  
  58.         android:text="Login" />  
  59.   
  60. </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.   
  5.     <EditText  
  6.         android:id="@+id/editText1"  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_alignParentTop="true"  
  10.         android:layout_centerHorizontal="true"  
  11.         android:layout_marginTop="15dp"  
  12.         android:ems="10"  
  13.         android:hint="Enter UserName" />  
  14.   
  15.     <EditText  
  16.         android:id="@+id/editText2"  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:layout_alignLeft="@+id/editText1"  
  20.         android:layout_below="@+id/editText1"  
  21.         android:layout_marginTop="50dp"  
  22.         android:ems="10"  
  23.         android:hint="Enter Password"  
  24.         android:inputType="textPassword" />  
  25.   
  26.     <Button  
  27.         android:id="@+id/button1"  
  28.         android:layout_width="wrap_content"  
  29.         android:layout_height="wrap_content"  
  30.         android:layout_alignParentBottom="true"  
  31.         android:layout_centerHorizontal="true"  
  32.         android:text="Resister" />  
  33.   
  34.     <ProgressBar  
  35.         android:id="@+id/progressBar1"  
  36.         style="?android:attr/progressBarStyleLarge"  
  37.         android:layout_width="wrap_content"  
  38.         android:layout_height="wrap_content"  
  39.         android:layout_alignLeft="@+id/button1"  
  40.         android:layout_below="@+id/editText2"  
  41.         android:layout_marginTop="87dp" />  
  42.   
  43. </RelativeLayout>  

MainActivity class

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

RegisterUser class

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

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.   
  7.     <uses-sdk  
  8.         android:minSdkVersion="8"  
  9.         android:targetSdkVersion="17" />  
  10.   
  11.     <uses-permission android:name="android.permission.INTERNET" />  
  12.   
  13.     <application  
  14.         android:allowBackup="true"  
  15.         android:icon="@drawable/ic_launcher"  
  16.         android:label="@string/app_name"  
  17.         android:theme="@style/AppTheme" >  
  18.         <activity  
  19.             android:name="com.example.newrestapi.MainActivity"  
  20.             android:label="@string/app_name" >  
  21.             <intent-filter>  
  22.                 <action android:name="android.intent.action.MAIN" />  
  23.   
  24.                 <category android:name="android.intent.category.LAUNCHER" />  
  25.             </intent-filter>  
  26.         </activity>  
  27.         <activity  
  28.             android:name="com.example.newrestapi.ResisterUser"  
  29.             android:label="@string/title_activity_resister_user" >  
  30.         </activity>  
  31.     </application>  
  32.   
  33. </manifest>  

Output:

android web service example output 1 android web service example output 2

Java Servlet Login and Register example using oracle database

Create table javatpoint_user in the oracle database having three columns id, name and password. Id must be primary key and generated through SEQUENCE.
  1. CREATE TABLE  "JAVATPOINT_USER"   
  2.    (    "ID" NUMBER,   
  3.     "NAME" VARCHAR2(4000),   
  4.     "PASSWORD" VARCHAR2(4000),   
  5.      CONSTRAINT "JAVATPOINT_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.   
  3. import java.io.IOException;  
  4. import java.io.ObjectOutputStream;  
  5. import java.sqlCONNECTION;  
  6. import java.sql.DriverManager;  
  7. import java.sql.PreparedStatement;  
  8. import java.sql.ResultSet;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.http.HttpServlet;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. public class Login extends HttpServlet {  
  15.   
  16.       
  17.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  18.             throws ServletException, IOException {  
  19.          response.setContentType("text/html");    
  20.              
  21.             ObjectOutputStream out=new ObjectOutputStream(response.getOutputStream());  
  22.                    
  23.             String n=request.getParameter("name");    
  24.             String p=request.getParameter("pass");  
  25.             System.out.println(n);  
  26.             System.out.println(p);  
  27.                     
  28.             if(validate(n, p)){    
  29.                out.writeObject("success");  
  30.               
  31.             }    
  32.             else{    
  33.                out.writeObject("Sorry username or password error");  
  34.                                  
  35.             }    
  36.                     
  37.             out.close();    
  38.             }    
  39.           
  40.       
  41.     public static boolean validate(String name,String pass){    
  42.         boolean status=false;    
  43.         try{    
  44.             Class.forName("oracle.jdbc.driver.OracleDriver");  
  45.             Connection con=DriverManager.getConnection(  
  46.                       "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");  
  47.                 
  48.         PreparedStatement ps=con.prepareStatement(    
  49.         "select * from javatpoint_user where name=? and password=?");    
  50.         ps.setString(1,name);    
  51.         ps.setString(2,pass);    
  52.                 
  53.         ResultSet rs=ps.executeQuery();    
  54.         status=rs.next();    
  55.                     
  56.         }catch(Exception e){System.out.println(e);}    
  57.         return status;    
  58.         }    
  59.     public void doPost(HttpServletRequest request,HttpServletResponse response)  
  60.     throws ServletException, IOException {  
  61. doGet(request, response);  
  62.   
  63. }  
  64. }  

httpPostServlet Servlet class

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

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>