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);
}
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
Post a Comment