Skip to main content

Volley for client and server interaction (Android)

Volley provides client and server interaction with QUEUE basis, each and every request process separately, we can cancel our request from QUEUE.

HERE is a code sample for Volley with json request format.

GenerateRequest.java

--------------------------------------------------------------------
package com.entrata.maintenance.network_communication.networkutils;
import android.content.Context;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.entrata.maintenance.application.ERPUserDefaults;
import com.entrata.maintenance.network_communication.networkconstant.NetworkConstant;
import com.entrata.maintenance.network_communication.networkexception.Error;
import com.entrata.maintenance.network_communication.networkutil.SubdomainChange;
import com.entrata.maintenance.utils.Logger;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class GenerateRequest {
    //region Field Declaration
    private static final String METHOD = "method";
    private static final String NAME = "name";
    private static final String AUTHORIZATION = "Authorization";
    private static final String AUTHORIZATION_DEV = "Authorization_Dev";
    private static final String RESULT = "result";
    private static final String ERROR = "error";
    private static final String TAG = GenerateRequest.class.getName();
    private static final String RESPONSE = "response";
    private NetworkResultListener networkResultListener;
    //endregion Field Declaration
    /**
     * @param request
     */
    public void addRequestToQueue(Context context, final JSONObject request, int requestType) throws JSONException, AuthFailureError {
        if (null != context) {
            final SubdomainChange subdomainChange = new SubdomainChange(context);
            final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(requestType, request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN)  ? subdomainChange.replaceLogin() : subdomainChange.replace(), request, success, error) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> header = new HashMap<>();
                    try {
                        if (!subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "").equals("") && !request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN)) {
                            header.put(AUTHORIZATION, String.format("Bearer %s", subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "")));
                            header.put("Content-Type", "application/json");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return header;
                }
            };
            NetworkHandler.getInstance(context).addToRequestQueue(jsonObjectRequest);
        }
    }
    /**
     * @param request
     */
    public JsonObjectRequest addRequestToQueues(Context context, final JSONObject request, int requestType) throws JSONException, AuthFailureError {
        JsonObjectRequest jsonObjectRequest = null;
        if (null != context) {
            final SubdomainChange subdomainChange = new SubdomainChange(context);
            jsonObjectRequest = new JsonObjectRequest(requestType, request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN) || request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.FORGOT_COMPANY_USER_PASSWORD) ? subdomainChange.replaceLogin() : subdomainChange.replace(), request, success, error) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> header = new HashMap<>();
                    try {
                        if (!subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "").equals("") && !request.getJSONObject(METHOD).optString(NAME).equalsIgnoreCase(NetworkConstant.MethodName.GET_ACCESS_TOKEN)) {
                            header.put(AUTHORIZATION, String.format("Bearer %s", subdomainChange.maintenancePreference.getString(ERPUserDefaults.ACCESSTOKEN, "")));
                            header.put("Content-Type", "application/json");
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    return header;
                }
            };
            NetworkHandler.getInstance(context).addToRequestQueue(jsonObjectRequest);
        }
        return jsonObjectRequest;
    }
    /**
     * @param networkResultListener
     */
    public void setNetworkResultListener(NetworkResultListener networkResultListener) {
        this.networkResultListener = networkResultListener;
    }
    Response.Listener<JSONObject> success = new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {
                if (null != response) {
                    JSONObject jsonObject = response;
                    if (null != jsonObject) {
                        if (jsonObject.getJSONObject(RESPONSE).has(RESULT)) {
                            networkResultListener.onSuccess(response);
                        } else if (jsonObject.getJSONObject(RESPONSE).has(ERROR)) {
                            Error error = new Gson().fromJson(jsonObject.getJSONObject(RESPONSE).getJSONObject(ERROR).toString(), Error.class);
                            networkResultListener.onError(error);
                        } else {
                            networkResultListener.onFailure(response);
                        }
                    } else {
                        networkResultListener.onFailure(response);
                    }
                } else {
                    networkResultListener.onFailure(response);
                }
            } catch (JSONException e) {
                Logger.print(TAG, e.toString());
            }
        }
    };
    Response.ErrorListener error = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            try {
                networkResultListener.onFailure(error);
            } catch (JSONException e) {
                Logger.print(TAG, e.toString());
            }
        }
    };
}

---------------------------------------------------------------------------

NetworkHandler.java

-------------------------------------------------------------------------
package com.entrata.maintenance.network_communication.networkutils;

import android.content.Context;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.Volley;
import com.entrata.maintenance.utils.Logger;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
 * @author Tatyabhau Chavan
 * @since 23/12/2016
 */
public class NetworkHandler {
    private static final String TAG = NetworkHandler.class.getName();
    private static RequestQueue requestQueue;
    private Context context;
    private static volatile NetworkHandler instance;
    private SSLSocketFactory sslFactory;
    private static final int MY_SOCKET_TIMEOUT_MS = 30000;
    private NetworkHandler(Context context) {
        this.context = context;
    }
    /**
     * @param context
     * @return instance
     */
    public static NetworkHandler getInstance(Context context) {
        NetworkHandler result = instance;
        if (null == result) {
            synchronized (NetworkHandler.class) {
                result = instance;
                if (null == result) {
                    instance = result = new NetworkHandler(context);
                }
            }
        }
        return instance;
    }
    /**
     * @return request queue
     */
    public synchronized RequestQueue getRequestQueue() {
        HurlStack hurlStack = new HurlStack(null, createSslSocketFactory());
        requestQueue = Volley.newRequestQueue(context.getApplicationContext(), hurlStack);
       // requestQueue = Volley.newRequestQueue(context.getApplicationContext());
        return requestQueue;
    }
    /**
     * @return factory
     */
    private static SSLSocketFactory createSslSocketFactory() {
        TrustManager[] byPassTrustManagers = new TrustManager[]{new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        SSLContext sslContext = null;
        SSLSocketFactory sslSocketFactory = null;
        HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
        try {
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, byPassTrustManagers, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
        } catch (NoSuchAlgorithmException e) {
            Logger.print(e.toString(), TAG);
        } catch (KeyManagementException e) {
        }
        return sslSocketFactory;
    }
    private static class NullHostNameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
    /**
     * @param request
     * @param <T>
     */
    public <T> void addToRequestQueue(Request<T> request) {
        request.setRetryPolicy(new DefaultRetryPolicy(
                MY_SOCKET_TIMEOUT_MS,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        getRequestQueue().add(request);
    }

}
------------------------------------------------------------------
NetworkResultListener.java
------------------------------------------------------------------
package com.entrata.maintenance.network_communication.networkutils;
import com.entrata.maintenance.network_communication.networkexception.Error;
import org.json.JSONException;

public interface NetworkResultListener<T> {
    void onSuccess(T success) throws JSONException;
    void onFailure(T failure) throws JSONException;
    void onError(Error error);
}




Comments

Popular posts from this blog

Java Code Examples for javax.net.ssl.HttpsURLConnection The following code examples are extracted from open source projects. You can click to vote up the examples you like. Your votes will be used in an intelligent system to get more and better code examples. Thanks for your votes! Code Example 1:   9  From project ADFS , under directory /adfs-hdfs-project/adfs-hdfs/src/main/java/org/apache/hadoop/hdfs/ . Source HsftpFileSystem.java @Override protected HttpURLConnection openConnection ( String path , String query ) throws IOException { query = addDelegationTokenParam ( query ); final URL url = new URL ( "https" , nnAddr . getHostName (), nnAddr . getPort (), path + '?' + query ); HttpsURLConnection conn =( HttpsURLConnection ) url . openConnection (); conn . setHostnameVerifier ( new DummyHostnameVerifier ()); return ( HttpURLConnection ) conn ; } Code Example 2:  ...

Improving Layout Performance

Improving Layout Performance Layouts are a key part of Android applications that directly affect the user experience. If implemented poorly, your layout can lead to a memory hungry application with slow UIs. The Android SDK includes tools to help you identify problems in your layout performance, which when combined the lessons here, you will be able to implement smooth scrolling interfaces with a minimum memory footprint. Lessons Optimizing Layout Hierarchies In the same way a complex web page can slow down load time, your layout hierarchy if too complex can also cause performance problems. This lesson shows how you can use SDK tools to inspect your layout and discover performance bottlenecks. Re-using Layouts with <include/> If your application UI repeats certain layout constructs in multiple places, this lesson shows you how to create efficient, re-usable layout constructs, then include them in the appropriate UI layouts. Loading Views On Demand Be...