REST API Call (Web Service) Using Volley Library

Volley overview

Volley is an HTTP library that makes networking for Android apps easier and most
importantly, faster.

Benefits:

  1. Automatic scheduling of network requests.
  2. Multiple concurrent network connections.
  3. Transparent disk and memory response caching with standard HTTP cache coherence.
  4. Support for request prioritization.
  5. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  6. Ease of customization, for example, for retry and backoff.
  7. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  8. Debugging and tracing tools
build.gradle :

Make Sure Add this dependency to build.gradle in your project.Then only we will get the entire import class and interfaces.

dependencies {
    ...
    compile 'com.android.volley:volley:1.1.0'
}
Here,I'm implement the HttpPost Service call in this Class.

HttpPostCall.Java
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

import java.util.HashMap;
import java.util.Map;

/** * Created by Raj Kumar on 2016-05-02. */
public class HttpPostCall {

    private Context context;

    private RequestProcess requestProcess;
    private String message;
    private int reqId = -1;
    private int typeError = -1;
    private static Dialog dialog = null;

    public HttpPostCall(final Context context, final RequestProcess requestProcess, String url, String postdata, int request) {
        this.context = context;
        this.requestProcess = requestProcess;
        this.reqId = request;

        requestProcess.requestStarted();

        JSONObject json = null;
        try {
            json = new JSONObject(postdata);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestQueue queue = Volley.newRequestQueue(context);
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, json,
                new Response.Listener<JSONObject>() {
                    @Override                    public void onResponse(JSONObject response) {
                        requestHandler.requestCompleted(response, reqId);
                    }
                }, new Response.ErrorListener() {
            @Override            public void onErrorResponse(VolleyError error) {
                if (error instanceof NetworkError) {

                    message = "Cannot connect to Internet...Please check your connection!";
                    showProgress(message, context);
                    typeError = 1;
                } else if (error instanceof ServerError) {
                    typeError = 2;
                    message = "The server could not be found. Please try again after some time!!";
                    showProgress(message, context);
                } else if (error instanceof AuthFailureError) {
                    typeError = 3;
                    message = "Cannot connect to Internet...Please check your connection!";
                    showProgress(message, context);
                } else if (error instanceof ParseError) {
                    typeError = 4;
                    message = "No Data Found";
                    showProgress(message, context);
                } else if (error instanceof NoConnectionError) {
                    typeError = 5;
                    message = "Cannot connect to Internet...Please check your connection!";
                    showProgress(message, context);
                } else if (error instanceof TimeoutError) {
                    typeError = 6;
                    message = "TimeOut! Please check your internet connection.";
                    showProgress(message, context);
                }
                requestProcess.requestEndedWithError(message, typeError);
            }

        }) {
            /** Passing some request headers* */            @Override            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap();
                headers.put("Content-Type", "application/json");
                return headers;
            }
        };
        queue.add(jsonObjectRequest);
    }

    public static void showProgress(String title, final Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title)

                .setCancelable(false)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();

                    }

                });
        AlertDialog alert = builder.create();
        alert.show();

    }
}
In the above class i mentioned one Interface is called RequestProcess.

  1.  The need of this interface It's contract between server and client.This implementaion call i mentioned below:
import org.json.JSONObject;
/** * Created by Raj Kumar on 2016-05-02. */
public interface RequestProcess {

    public void requestStarted();

    public void requestCompleted(JSONObject response,int requestType);

    public void requestEndedWithError(String error, int errorcode);

}
Once completed above then implement the Json webservice  call behavior below:

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity implements RequestProcess {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.youlayoutname);

        callYourService();
    }

    private void callYourService() {

        JSONObject object = new JSONObject();
        object.put("stringdata",code);

        new HttpPostResquest(this, this, url, object.toString(), 1);
    }

    @Override    public void requestStarted() {

        //write code here to processing bar    }

    @Override    public void requestCompleted(JSONObject response, int requestType) {
        // write you code here response data.    }

    @Override    public void requestEndedWithError(String error, int ecode) {
        // write your code while getting error    }
} 

Comments

Post a Comment