Skip to content

Instantly share code, notes, and snippets.

@ishmaelmakitla
Created May 9, 2016 21:49
Show Gist options
  • Save ishmaelmakitla/c871054181dc7ae5a43564813cb47284 to your computer and use it in GitHub Desktop.
Save ishmaelmakitla/c871054181dc7ae5a43564813cb47284 to your computer and use it in GitHub Desktop.
package za.co.ishlema.blog.examples;
import java.util.HashMap;
import java.util.Map.Entry;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonRequest;
/**
This is an example of a custom JsonRequest using Volley. In this case, I create a login request which sends the username and password
to the server pointed to by the 'url' value
@author Ishmael Makitla
*/
public class LoginJsonRequest extends JsonRequest<JSONObject>{
private HashMap<String, String> responseHeaders = new HashMap<String, String>();
public LoginJsonRequest(int method, String url, String requestBody,Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, requestBody, listener, errorListener);
}
public LoginJsonRequest(int method, String url, JSONObject jsonRequestBody,Listener<JSONObject> listener, ErrorListener errorListener){
super(method, url, jsonRequestBody.toString(), listener, errorListener);
}
@Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
String data = new String (response.data);
JSONObject jsonResponse = null;
try {
jsonResponse = new JSONObject(data);
} catch (JSONException e) {
e.printStackTrace();
}
getResponseHeader();
return Response.success(jsonResponse, getCacheEntry());
}
public HashMap<String, String> getResponseHeader(){
try {
responseHeaders.putAll(super.getHeaders());
} catch (AuthFailureError e) {
e.printStackTrace();
}
StringBuilder builder = new StringBuilder();
for(Entry<String, String> entry : responseHeaders.entrySet()){
builder.append(entry.getKey());
builder.append("=");
builder.append(entry.getValue());
builder.append("\r");
}
return responseHeaders;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment