anyone has an example, where you read a protobuf, using volley?. I have read that you can implement ProtobufRequest class, but I can not find documentation for it. Thank you for your help.
I have done it,the work is ok,hope it is helpful.first create the ProtobufRequest class like below that extends Request,Request is the basic request class in Volley,then,you can create the custom request extends ProtobufRequest that do custom doParse().just as a reference.
RequestData is SomeProto message,
private static final int SOCKET_TIMEOUT = 30000;
/** Content type for request. */
private static final String PROTOCOL_CONTENT_TYPE = "application/x-protobuf";
private static final Object sDecodeLock = new Object();
private RequestData mRequestData;
private BaseCallback mCallback;
public ProtobufRequest(RequestData data, BaseCallback callback) {
super(Method.POST, Constants.SERVER_URL, callback);
// TODO Auto-generated constructor stub
mRequestData = data;
mCallback = callback;
this.setRetryPolicy(getRetryPolicy());
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Charset", "UTF-8");
headers.put("Content-Type", "application/x-protobuf");
headers.put("Accept", "application/x-protobuf");
return headers;
}
#Override
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
}
#Override
public RetryPolicy getRetryPolicy() {
RetryPolicy retryPolicy = new DefaultRetryPolicy(SOCKET_TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return retryPolicy;
}
/**
** write the protobuf data to http request,it is very important
*/
#Override
public byte[] getBody() throws AuthFailureError {
if (mRequestData == null) {
return super.getBody();
} else {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
baos.write(mRequestData.toByteArray());
} catch (IOException e) {
return super.getBody();
}
return baos.toByteArray();
}
}
#Override
protected void deliverResponse(Object arg0) {
mCallback.onResponse(arg0);
}
/**
** parse the response result
*/
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
synchronized (sDecodeLock) {
try {
return doParse(response, HttpHeaderParser.parseCacheHeaders(response));
} catch (OutOfMemoryError e) {
return Response.error(new ParseError(e));
}
}
}
abstract protected Response<T> doParse(NetworkResponse response, Entry entry)
public interface BaseCallback extends Listener<Object>, ErrorListener {
}
From: cmcneil Added code in case link rot. There should be an official implementation by Volley or Protocol Buffers eventually so please update this when necessary.
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.protobuf.MessageLite;
import java.util.HashMap;
import java.util.Map;
/**
* Created by carson#convox.org on 5/10/15.
*/
public class ProtoBufRequest<ReqT extends MessageLite, RespT extends MessageLite> extends Request<RespT> {
private ReqT request;
private final Class<RespT> responseType;
private final Listener<RespT> listener;
private static final String PROTOCOL_CONTENT_TYPE = "application/x-protobuf";
private static final int SOCKET_TIMEOUT = 30000;
public ProtoBufRequest(int method, String url, ReqT data, Class<RespT> responseType,
Listener<RespT> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.request = data;
this.responseType = responseType;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Charset", "UTF-8");
headers.put("Content-Type", PROTOCOL_CONTENT_TYPE);
headers.put("Accept", PROTOCOL_CONTENT_TYPE);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
if (request == null) {
return super.getBody();
}
return request.toByteArray();
}
#Override
protected Response<RespT> parseNetworkResponse(NetworkResponse response) {
try {
if (responseType == null) {
throw new IllegalArgumentException("The response type was never provided.");
}
RespT responseInstance = responseType.newInstance();
return (Response<RespT>) Response.success(
responseInstance.newBuilderForType().mergeFrom(response.data).build(),
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
e.printStackTrace();
return Response.error(new ParseError(e));
}
}
#Override
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
}
#Override
public RetryPolicy getRetryPolicy() {
RetryPolicy retryPolicy = new DefaultRetryPolicy(SOCKET_TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return retryPolicy;
}
#Override
protected void deliverResponse(RespT response) {
listener.onResponse(response);
}
}
This is not an example and I have not (yet) done it myself but here is how I would do it:
One way is to extend JsonObjectRequest and serialize and deserialize every protocol buffer as Json using:
Message someProto = SomeProto.getDefaultInstance();
String jsonFormat = JsonFormat.printToString(someProto);
Message.Builder builder = SomeProto.newBuilder();
String jsonFormat = _load json document from a source_;
JsonFormat.merge(jsonFormat, builder);
See: https://code.google.com/p/protobuf-java-format/
Otherwise, if you want to send the protocol buffer serialize to byte[] you could extend Request<T>. The you would override public byte[] getBody() for the request body/payload, and
protected Response<Message> parseNetworkResponse(NetworkResponse response) for the answer.
You would then use the following functions to serialize the protocol buffer.
byte[] toByteArray();
parseFrom(byte[] data);
If you have a solution do not forget to share.
Just sticking this here in case it's useful:
I searched around a lot for a generic way to do something similar to jeff wang's answer. I couldn't find anything so I wrote this.
Let me know if you have any way to get rid of the unchecked cast in there...
ProtobufRequest.java
public class ProtoBufRequest<ReqT extends Message, RespT extends Message> extends Request<RespT> {
private ReqT request;
private final Class<RespT> responseType;
private final Listener<RespT> listener;
private static final String PROTOCOL_CONTENT_TYPE = "application/x-protobuf";
private static final int SOCKET_TIMEOUT = 30000;
public ProtoBufRequest(int method, String url, ReqT data, Class<RespT> responseType,
Listener<RespT> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.listener = listener;
this.request = data;
this.responseType = responseType;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Charset", "UTF-8");
headers.put("Content-Type", PROTOCOL_CONTENT_TYPE);
headers.put("Accept", PROTOCOL_CONTENT_TYPE);
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
if (request == null) {
return super.getBody();
}
return request.toByteArray();
}
#Override
protected Response<RespT> parseNetworkResponse(NetworkResponse response) {
try {
if (responseType == null) {
throw new IllegalArgumentException("The response type was never provided.");
}
RespT responseInstance = responseType.newInstance();
return (Response<RespT>) Response.success(
responseInstance.newBuilderForType().mergeFrom(response.data).build(),
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
e.printStackTrace();
return Response.error(new ParseError(e));
}
}
#Override
public String getBodyContentType() {
return PROTOCOL_CONTENT_TYPE;
}
#Override
public RetryPolicy getRetryPolicy() {
RetryPolicy retryPolicy = new DefaultRetryPolicy(SOCKET_TIMEOUT,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return retryPolicy;
}
#Override
protected void deliverResponse(RespT response) {
listener.onResponse(response);
}
}
Related
What have I done wrong?. How can i resolve this?. Please explain why this error occur. if it is run successfully what is my response?
MainActivity :
public class MainActivity extends AppCompatActivity {
String url = "http://vsstechnology.com/DTSignUp/api/business/create_business.php";
String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
HashMap<String, String> params = new HashMap<>();
params.put("address", "xxx");
params.put("business_description", "xx");
params.put("businessEmail", "xxx#gmail.com");
params.put("business_name", "xxx");
params.put("phone", "1234567890");
params.put("business_type", "xx");
params.put("created_by", "xxx");
params.put("customer_name", "xxx");
params.put("email", "yyy#gmail.com");
params.put("firstName", "yyy");
params.put("lastName", "yyy");
params.put("phone", "6544324569");
GsonRequest<Model> gsonRequest = new GsonRequest<Model>(Request.Method.POST, url, Model.class, params, new Response.Listener<Model>() {
#Override
public void onResponse(Model response) {
Toast.makeText(getApplicationContext(), "success" + " " + response, Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "error" + " " + error, Toast.LENGTH_LONG).show();
}
});
requestQueue.add(gsonRequest);
}
}
Model :
public class Model {
private Business business;
private Contacts[] contacts;
private ServerResponse serverResponse;
public Model(Business business, Contacts[] contacts, ServerResponse serverResponse) {
this.business = business;
this.contacts = contacts;
this.serverResponse = serverResponse;
}
public Business getBusiness() {
return business;
}
public void setBusiness(Business business) {
this.business = business;
}
public Contacts[] getContacts() {
return contacts;
}
public void setContacts(Contacts[] contacts) {
this.contacts = contacts;
}
public ServerResponse getServerResponse() {
return serverResponse;
}
public void setServerResponse(ServerResponse serverResponse) {
this.serverResponse = serverResponse;
}
}
custom GsonRequest :
public class GsonRequest<T> extends Request<T> {
private Gson gson = new Gson();
private Class<T> clazz;
private Map<String, String> headers;
private Map<String, String> params;
private Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param params Map of request headers
*/
public GsonRequest(int method, String url, Class<T> clazz, Map<String, String> params,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.clazz = clazz;
this.headers = null;
this.params = params;
this.listener = listener;
gson = new Gson();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
Error :
com.android.volley.ParseError : com.Google.gson.JsonSyntaxException:
java.lang.illegalStateException: Expected BEGIN_OBJECT but was STRING
at line 1 column 1 path $
Based on your error some thing is wrong with your API, to debug it you can use Postman.
I am using Google's Volley to make GET and POST requests using the following custom request class:
public class GsonRequest<T> extends Request<T> {
private static final int SOCKET_TIMEOUT_MS = 30000;
private static final int MAX_RETRIES = 3;
private final Gson gson = new Gson();
private final Type type;
private final Map<String, String> params;
private final Response.Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param type Relevant type object, for Gson's reflection
* #param params Map of request params
*/
public GsonRequest(int method, String url, Type type, Map<String, String> params,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(method, url, errorListener);
this.type = type;
this.params = params;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// Here is my question, can I add a param value as JSONArray? like this:
params.put("orderValue", "35");
params.put("price", ""price": ["13.00", "22.00"]");
return params != null ? params : super.getParams();
}
#Override
public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
final RetryPolicy policy = new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return super.setRetryPolicy(policy);
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
Log.i("" + gson.toJson(params).getBytes("utf-8"));
return gson.toJson(params).getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", gson.toJson(params), "utf-8");
return super.getBody();
}
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
final String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return (Response<T>) Response.success(gson.fromJson(json, type), HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
The Json I'm trying to send:
{
"orderValue": "35",
"price": [
"13.00",
"22.00"
]
}
What is really sent as I get from getBody() method log is:
{
"price": "[\"23.00\",\"55.00\"]",
"orderValue": "35"
}
Any help with this issue?
You need change extends Request to ** JsonObjectRequest** or create JSONArrayRequest object.
public class VolleyJSONObjectRequest extends JsonObjectRequest {
private Context context;
private int timeOut = 10000;
private int maxRetries = 1;
public VolleyJSONObjectRequest(int method, Context context, String url, JSONObject jsonObject, Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, jsonObject, listener, errorListener);
super.setRetryPolicy(new DefaultRetryPolicy(timeOut, maxRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void startRequest() {
VolleyHandler.get(context).addToRequestQueue(this);
}
}
Example method:
private void saveItems(){
if (itens != null && itens.size() > 0) {
try {
JSONArray itensJson = new JSONArray();
for (SalesOrderItem item : itens) { // your loop
JSONObject jsonObject = new JSONObject();
jsonObject.put("price", this.priceOne);
jsonObject.put("price", this.priceTwo);
itensJson.put(jsonObject);
}
JSONObject headerJSON = new JSONObject();
headerJSON.put("price", itensJson);
VolleyJSONObjectRequest request = new VolleyJSONObjectRequest(Request.Method.POST, context, context.getString(R.string.URL_SALES_ORDER_ITENS_INSERT), headerJSON, onResponseItem, onErrorResponseItem);
request.startRequest();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
request = new VolleyStringRequest(context, context.getString(R.string.URL_FINISH_SALES_ORDER_DRAFT), onResponseFinishSalesOrderDraft, onErrorResponseFinishSalesOrderDraft);
request.startRequest();
am new to android can any one answer for this question please, i tried alot but didn't find correct stuff.i want to send a my custom user object to spring rest service
Employee Object:
in android and spring
public class Employee{
String firstname;
String lastname;
//setters and getter goes here
}
GsonRequest:
public class GsonRequest<T> extends Request<T> {
public final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
private final Object dataIn;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
this.dataIn = null;
}
public GsonRequest(String url, Object dataIn, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.dataIn = dataIn;
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
#Override
public byte[] getBody() throws AuthFailureError {
return gson.toJson(dataIn).getBytes();
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
}
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
Button clickbtn;
TextView resText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
clickbtn=(Button)findViewById(R.id.mybutton);
resText=(TextView)findViewById(R.id.mytext);
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Employee emp=new Employee();
emp.setFirstname("naresh");
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
GsonRequest<Employee> myReq = new GsonRequest<Employee>("http://192.168.10.37:8088/adduser",
emp,
Employee.class,
new HashMap<String, String>(),
new Response.Listener<Employee>() {
#Override
public void onResponse(Employee response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"error", Toast.LENGTH_SHORT).show();
Log.i("post error","post error",error);
resText.setText(error.getMessage());
Log.d("post error","post error",error);
}
});
queue.add(myReq);
}
});
}
}
spring rest service:
#RequestMapping("adduser")
public void addUser(#Requestbody User user){
Sysetm.out.println(user.getFirstname());
}
Exception:
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
E/Volley: [216] BasicNetwork.performRequest: Unexpected response code 415 for http://192.168.10.37:8088/adduser
I/post error: post error
com.android.volley.ServerError
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
D/post error: post error
com.android.volley.ServerError
at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:163)
at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
As my comment, please add headers.put("Content-Type", "application/json; charset=utf-8"); inside getHeaders().
In Android, I am making an HTTP file upload request to a server as follows
MultipartRequest multipartRequest = new MultipartRequest(uploadUrl, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() {
#Override
public void onResponse(NetworkResponse response) {
// Need to read Json response here
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(GlobalClass.TAG, "File not uploaded");
}
});
GlobalClass.getInstance().addToRequestQueue(multipartRequest);
}
The response is of the following structure:
{
'response': 'some_data_to_be_used'
}
And this is my MultipartRequest class:
package com.xxxxxx.xxxxxx;
import android.util.Log;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import java.util.Map;
class MultipartRequest extends Request<NetworkResponse> {
private final Response.Listener<NetworkResponse> mListener;
private final Response.ErrorListener mErrorListener;
private final Map<String, String> mHeaders;
private final String mMimeType;
private final byte[] mMultipartBody;
public MultipartRequest(String url, Map<String, String> headers, String mimeType, byte[] multipartBody, Response.Listener<NetworkResponse> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.mListener = listener;
this.mErrorListener = errorListener;
this.mHeaders = headers;
this.mMimeType = mimeType;
this.mMultipartBody = multipartBody;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return (mHeaders != null) ? mHeaders : super.getHeaders();
}
#Override
public String getBodyContentType() {
return mMimeType;
}
#Override
public byte[] getBody() throws AuthFailureError {
return mMultipartBody;
}
#Override
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
#Override
protected void deliverResponse(NetworkResponse response) {
Log.d(GlobalClass.TAG, response.toString());
mListener.onResponse(response);
}
#Override
public void deliverError(VolleyError error) {
mErrorListener.onErrorResponse(error);
}
}
In my parseNetworkResponse method, I've tried the following:
protected Response<NetworkResponse> parseNetworkResponse(NetworkResponse response) {
try {
Log.d(GlobalClass.TAG, response.toString());
String json = new String(response.data, HttpHeaderParser.parseCacheHeaders(response));
return Response.success(
response,
HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError(e));
}
}
Which I got from here.
But this gives me the error Cannot resolve constructor String(byte[],com.android.volley.Cache.Entry).
How do I read the JSON response object and use the value of the response key as a string?
Update
As mentioned in the link you provided, you should change this line :
String json = new String(response.data, HttpHeaderParser.parseCacheHeaders(response));
to
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
This is because String class doesn't have any contructor that matches the one you used in your code,
hello.
I want to make a post request using gson.
I got the class implemented into android website...
http://developer.android.com/intl/pt-br/training/volley/request-custom.html
UserRequestHelper.userRequest(Request.Method.POST, EndpointURL.USUARIO, null, new Response.Listener<Usuario>() {
#Override
public void onResponse(Usuario response) {
Toast.makeText(getActivity(), "Cadastro realizado com sucesso!", Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getActivity(), "Erro ao realizar cadastro.", Toast.LENGTH_SHORT).show();
}
});
I need a body to send the user? How i send the object user to make a post request?
Could someone help me with this?
you have to override getBody :
#Override
public byte[] getBody() throws AuthFailureError {
return gson.toJson(dataIn).getBytes();
}
the whole example class(form the same link) edited:
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Response.Listener<T> listener;
private final Object dataIn;
/**
* Make a GET request and return a parsed object from JSON.
*
* #param url URL of the request to make
* #param clazz Relevant class object, for Gson's reflection
* #param headers Map of request headers
*/
public GsonRequest(String url, Object dataIn, Class<T> clazz, Map<String, String> headers,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
super(Method.POST, url, errorListener);
this.dataIn = dataIn;
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
#Override
public byte[] getBody() throws AuthFailureError {
return gson.toJson(dataIn).getBytes();
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}