Showing posts with label Webservice. Show all posts
Showing posts with label Webservice. Show all posts

Tuesday, November 22, 2016

Simple Webservice

A web service is a standard for exchanging information between different types of applications irrespective of language and platform. 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.



 Steps to call web service in your project.

  1. Crate a project in android studio.
  2. Open manifest.xml and add a permission to it.

     
    <uses-permission android:name="android.permission.INTERNET" />
     
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.pankaj.simple.webservice">
    
        <!--permissions-->
        <uses-permission android:name="android.permission.INTERNET" />
    
        <!--application-->
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
    
            <!--activities-->
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    </manifest>
    

     
  3. Open build.gradle(app) and add

    apply plugin: 'com.android.application'
    android {
    
        compileSdkVersion 23
        buildToolsVersion "23.0.2"
    
        defaultConfig {
            applicationId "com.pankaj.simple.webservice"
            minSdkVersion 15
            targetSdkVersion 23
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
    
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    /*___________add legacy for_____________*/
    android {
        useLibrary 'org.apache.http.legacy'
    }
    
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
            exclude group: 'com.android.support', module: 'support-annotations'
        })
        compile 'com.android.support:appcompat-v7:23.2.1'
        testCompile 'junit:junit:4.12'
    }
     
  4. Create JSONParser.Java class to handle web service operation

    package com.pankaj.simple.webservice;
    import android.os.AsyncTask;
    import android.util.Log;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.ClientProtocolException;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.client.utils.URLEncodedUtils;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.params.HttpParams;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.util.List;
    
    public class JSONParser {
    
        static InputStream is = null;
        static JSONArray jObj = new JSONArray();
        static String json = "";
        private String _url;
        private List<NameValuePair> _params;
    
        // constructor
        public JSONParser() {
        }
    
        // function get json from url
        // by making HTTP POST or GET mehtod
        public JSONObject makeHttpRequest2(String url, String method, List<NameValuePair> params) {
    
            // Making HTTP request
            try {
    
                // check for request method
                if (method == "POST") {
    
                    // request method is POST
                    // defaultHttpClient
                    HttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                } else if (method == "GET") {
    
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
    
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
                Log.v("json", json);
    
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            JSONObject jObj = null;
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
        }
    /*________not in use this will be use in next level webservicess_________________*/
    /*______________________start________________________________*/
        public JSONArray makeHttpRequest(String url, String method,
                                         List<NameValuePair> params) {
            // Making HTTP request
            try {
                // check for request method
                if (method == "POST") {
                    // request method is POST
                    // defaultHttpClient
    
                    DefaultHttpClient httpClient = new DefaultHttpClient();
    
                    HttpPost httpPost = new HttpPost(url);
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                    //httpPost.addHeader("test", "test");
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
                } else if (method == "GET") {
    
                    // request method is GET
                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    String paramString = URLEncodedUtils.format(params, "utf-8");
                    url += "?" + paramString;
                    HttpGet httpGet = new HttpGet(url);
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();
    
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
    
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
    
                is.close();
                json = sb.toString();
                Log.v("json", json);
    
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
    
                jObj = new JSONArray(json);
            } catch (JSONException e) {
    
                Log.e("JSON Parser", "Error parsing data " + e.toString());
                try {
                    jObj = new JSONArray("[{\"status\":\"failure\"}]");
                } catch (JSONException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
    
            }
    
            // return JSON String
            return jObj;
        }
    
        public static void setTcpNoDelay(HttpParams params, boolean value) {
            System.out.println("asd");
        }
    
        public static String getJSONString(String url) {
            String jsonString = null;
            HttpURLConnection linkConnection = null;
            try {
    
                URL linkurl = new URL(url);
                linkConnection = (HttpURLConnection) linkurl.openConnection();
                int responseCode = linkConnection.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    InputStream linkinStream = linkConnection.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int j = 0;
                    while ((j = linkinStream.read()) != -1) {
                        baos.write(j);
                    }
                    byte[] data = baos.toByteArray();
                    jsonString = new String(data);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (linkConnection != null) {
                    linkConnection.disconnect();
                }
            }
            return jsonString;
        }
    
    }
     
  5. Open activity_main.xml and update this

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 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"
        tools:context="com.pankaj.simple.webservice.MainActivity">
    
     
        <!--button to click for call webservice-->
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="callService"
            android:text="Call Service" />
    
    </RelativeLayout>
    
     
  6. Open MainActivity.Java and update this like below codes


    package com.pankaj.simple.webservice;
    import android.app.ProgressDialog;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Log;
    import android.view.View;
    import android.widget.Toast;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.util.ArrayList;
    import java.util.List;
    
    public class MainActivity extends AppCompatActivity {
    
        boolean showLoader = true;//if you want to show loader view then put showLoader = true, else showLoader = false
        String TAG = "tag_webservice";
        String webservice = "Enter your webservice here";//like  ;- http://servername/apppath/webservicename.php
    
        String RESPONSE_SUCCESS = "success";
        List<NameValuePair> params = new ArrayList<>();//this is the required parameter
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void callService(View view) {
            params.add(new BasicNameValuePair("parameterName1", "value1"));
            params.add(new BasicNameValuePair("parameterName2", "value2"));
            //add more parameter same as above
    
            //call webservice
            if (webservice.equalsIgnoreCase("Enter your webservice here")) {
                Toast.makeText(this, "Enter webservice first", Toast.LENGTH_SHORT).show();
            } else {
                new LoadDataAsyncTask().execute();
            }
        }
    
        //webservice
        class LoadDataAsyncTask extends AsyncTask<String, Void, JSONObject> {
            String status;
            ProgressDialog dialog;
    
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = new ProgressDialog(MainActivity.this);
                dialog.setMessage("Please wait...");
                dialog.setCanceledOnTouchOutside(false);
                if (showLoader) {
                    dialog.show();
                }
            }
    
            @Override
            protected JSONObject doInBackground(String... args) {
                Log.e(TAG, "params=" + params);
                Log.e(TAG, "webservice=" + webservice);
                JSONObject json = new JSONParser().makeHttpRequest2(webservice, "POST", params);
                return json;
            }
    
            //update your ui according to recieved data
            @Override
            protected void onPostExecute(JSONObject jsonObject) {
                super.onPostExecute(jsonObject);
                if (showLoader) {
                    dialog.dismiss();
                }
                try {
                    Log.e(TAG, "webservice_responce=" + jsonObject.toString());
    //                yow will recieve responce like this
    //                webservice_responce={"is_array":1,"message":"success","result":"test result"}
                    status = jsonObject.getString("message");
                    if (status.equals(RESPONSE_SUCCESS)) {
                        String is_array = jsonObject.getString("is_array");
                        String result = jsonObject.getString("result");
                    } else {
                        Toast.makeText(MainActivity.this, status, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
      
  7. Now run your application.

  8. click on "Call Service" Button and
    after some moment you will receive responce like -
    webservice_responce={"is_array":1,"message":"success","result":"
    test result"}
  9. Now parse data in on post methode -

    protected void onPostExecute(JSONObject jsonObject) {
                super.onPostExecute(jsonObject);
                if (showLoader) {
                    dialog.dismiss();
                }
                try {
                    Log.e(TAG, "webservice_responce=" + jsonObject.toString());
    //                yow will recieve responce like this
    //                webservice_responce={"is_array":1,"message":"success","result":"test result"}
                    status = jsonObject.getString("message");
                    if (status.equals(RESPONSE_SUCCESS)) {
                        String is_array = jsonObject.getString("is_array");
                        String result = jsonObject.getString("result");
                    } else {
                        Toast.makeText(MainActivity.this, status, Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
    

    
    
     
     
  10.  Good bye, Thanks to read this blog.