How to send JSON raw data using volley [duplicate] - android

I would like to send a new JsonObjectRequest request:
I want to receive JSON data (response from server): OK
I want to send JSON formatted data with this request to the server
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST, "myurl.com", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//...
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//...
}
})
{
#Override
protected Map<String,String> getParams() {
// something to do here ??
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
// something to do here ??
return params;
}
};
P.S. I use GSON library in my project too.

JsonObjectRequest actually accepts JSONObject as body.
From this blog article,
final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
Here is the source code and JavaDoc (#param jsonRequest):
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}

I know that this thread is quite old, but I had this problem and I came up with a cool solution which can be very useful to many because it corrects/extended the Volley library on many aspects.
I spotted some not supported-out-of-box Volley features:
This JSONObjectRequest is not perfect: you have to expect a JSON at the end (see the Response.Listener<JSONObject>).
What about Empty Responses (just with a 200 status)?
What do I do if I want directly my POJO from the ResponseListener?
I more or less compiled a lot of solutions in a big generic class in order to have a solution for all the problem I quoted.
/**
* Created by laurentmeyer on 25/07/15.
*/
public class GenericRequest<T> extends JsonRequest<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
// Used for request which do not return anything from the server
private boolean muteRequest = false;
/**
* Basically, this is the constructor which is called by the others.
* It allows you to send an object of type A to the server and expect a JSON representing a object of type B.
* The problem with the #JsonObjectRequest is that you expect a JSON at the end.
* We can do better than that, we can directly receive our POJO.
* That's what this class does.
*
* #param method: HTTP Method
* #param classtype: Classtype to parse the JSON coming from the server
* #param url: url to be called
* #param requestBody: The body being sent
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
*/
private GenericRequest(int method, Class<T> classtype, String url, String requestBody,
Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
super(method, url, requestBody, listener,
errorListener);
clazz = classtype;
this.headers = headers;
configureRequest();
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (with headers and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, headers);
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (without header and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, new HashMap<String, String>());
}
/**
* Method to be called if you want to send something to the server but not with a JSON, just with a defined String (without header and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param requestBody: String to be sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
*/
public GenericRequest(int method, String url, Class<T> classtype, String requestBody,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(method, classtype, url, requestBody, listener,
errorListener, new HashMap<String, String>());
}
/**
* Method to be called if you want to GET something from the server and receive the POJO directly after the call (no JSON). (Without header)
*
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
*/
public GenericRequest(String url, Class<T> classtype, Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(Request.Method.GET, url, classtype, "", listener, errorListener);
}
/**
* Method to be called if you want to GET something from the server and receive the POJO directly after the call (no JSON). (With headers)
*
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
*/
public GenericRequest(String url, Class<T> classtype, Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
this(Request.Method.GET, classtype, url, "", listener, errorListener, headers);
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (with headers and muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
* #param mute: Muted (put it to true, to make sense)
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers, boolean mute) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, headers);
this.muteRequest = mute;
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (without header and muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param mute: Muted (put it to true, to make sense)
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener, boolean mute) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, new HashMap<String, String>());
this.muteRequest = mute;
}
/**
* Method to be called if you want to send something to the server but not with a JSON, just with a defined String (without header and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param requestBody: String to be sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param mute: Muted (put it to true, to make sense)
*/
public GenericRequest(int method, String url, Class<T> classtype, String requestBody,
Response.Listener<T> listener, Response.ErrorListener errorListener, boolean mute) {
this(method, classtype, url, requestBody, listener,
errorListener, new HashMap<String, String>());
this.muteRequest = mute;
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
// The magic of the mute request happens here
if (muteRequest) {
if (response.statusCode >= 200 && response.statusCode <= 299) {
// If the status is correct, we return a success but with a null object, because the server didn't return anything
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
}
} else {
try {
// If it's not muted; we just need to create our POJO from the returned JSON and handle correctly the errors
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
T parsedObject = gson.fromJson(json, clazz);
return Response.success(parsedObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
return null;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
private void configureRequest() {
// Set retry policy
// Add headers, for auth for example
// ...
}
}
It could seem a bit overkill but it's pretty cool to have all these constructors because you have all the cases:
(The main constructor wasn't meant to be used directly although it's, of course, possible).
Request with response parsed to POJO / Headers manually set / POJO to Send
Request with response parsed to POJO / POJO to Send
Request with response parsed to POJO / String to Send
Request with response parsed to POJO (GET)
Request with response parsed to POJO (GET) / Headers manually set
Request with no response (200 - Empty Body) / Headers manually set / POJO to Send
Request with no response (200 - Empty Body) / POJO to Send
Request with no response (200 - Empty Body) / String to Send
Of course, in order that it works, you have to have Google's GSON Lib; just add:
compile 'com.google.code.gson:gson:x.y.z'
to your dependencies (current version is 2.3.1).

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
refer

final String url = "some/url";
instead of:
final JSONObject jsonBody = "{\"type\":\"example\"}";
you can use:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("type", "my type");
} catch (JSONException e) {
e.printStackTrace();
}
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

You can also send data by overriding getBody() method of JsonObjectRequest class. As shown below.
#Override
public byte[] getBody()
{
JSONObject jsonObject = new JSONObject();
String body = null;
try
{
jsonObject.put("username", "user123");
jsonObject.put("password", "Pass123");
body = jsonObject.toString();
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
return body.toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}

final Map<String,String> params = new HashMap<String,String>();
params.put("email", customer.getEmail());
params.put("password", customer.getPassword());
String url = Constants.BASE_URL+"login";
doWebRequestPost(url, params);
public void doWebRequestPost(String url, final Map<String,String> json){
getmDialogListener().showDialog();
StringRequest post = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
getmDialogListener().dismissDialog();
response....
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(App.TAG,error.toString());
getmDialogListener().dismissDialog();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = json;
return map;
}
};
App.getInstance().getRequestQueue().add(post);
}

protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
JSONObject JObj = new JSONObject();
try {
JObj.put("Id","1");
JObj.put("Name", "abc");
} catch (Exception e) {
e.printStackTrace();
}
params.put("params", JObj.toString());
// Map.Entry<String,String>
Log.d("Parameter", params.toString());
return params;
}

Related

How to send array index data to server in android through Volley Library? [duplicate]

I would like to send a new JsonObjectRequest request:
I want to receive JSON data (response from server): OK
I want to send JSON formatted data with this request to the server
JsonObjectRequest request = new JsonObjectRequest(
Request.Method.POST, "myurl.com", null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//...
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//...
}
})
{
#Override
protected Map<String,String> getParams() {
// something to do here ??
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
// something to do here ??
return params;
}
};
P.S. I use GSON library in my project too.
JsonObjectRequest actually accepts JSONObject as body.
From this blog article,
final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
Here is the source code and JavaDoc (#param jsonRequest):
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
Listener<JSONObject> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
I know that this thread is quite old, but I had this problem and I came up with a cool solution which can be very useful to many because it corrects/extended the Volley library on many aspects.
I spotted some not supported-out-of-box Volley features:
This JSONObjectRequest is not perfect: you have to expect a JSON at the end (see the Response.Listener<JSONObject>).
What about Empty Responses (just with a 200 status)?
What do I do if I want directly my POJO from the ResponseListener?
I more or less compiled a lot of solutions in a big generic class in order to have a solution for all the problem I quoted.
/**
* Created by laurentmeyer on 25/07/15.
*/
public class GenericRequest<T> extends JsonRequest<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
// Used for request which do not return anything from the server
private boolean muteRequest = false;
/**
* Basically, this is the constructor which is called by the others.
* It allows you to send an object of type A to the server and expect a JSON representing a object of type B.
* The problem with the #JsonObjectRequest is that you expect a JSON at the end.
* We can do better than that, we can directly receive our POJO.
* That's what this class does.
*
* #param method: HTTP Method
* #param classtype: Classtype to parse the JSON coming from the server
* #param url: url to be called
* #param requestBody: The body being sent
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
*/
private GenericRequest(int method, Class<T> classtype, String url, String requestBody,
Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
super(method, url, requestBody, listener,
errorListener);
clazz = classtype;
this.headers = headers;
configureRequest();
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (with headers and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, headers);
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (without header and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, new HashMap<String, String>());
}
/**
* Method to be called if you want to send something to the server but not with a JSON, just with a defined String (without header and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param requestBody: String to be sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
*/
public GenericRequest(int method, String url, Class<T> classtype, String requestBody,
Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(method, classtype, url, requestBody, listener,
errorListener, new HashMap<String, String>());
}
/**
* Method to be called if you want to GET something from the server and receive the POJO directly after the call (no JSON). (Without header)
*
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
*/
public GenericRequest(String url, Class<T> classtype, Response.Listener<T> listener, Response.ErrorListener errorListener) {
this(Request.Method.GET, url, classtype, "", listener, errorListener);
}
/**
* Method to be called if you want to GET something from the server and receive the POJO directly after the call (no JSON). (With headers)
*
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
*/
public GenericRequest(String url, Class<T> classtype, Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers) {
this(Request.Method.GET, classtype, url, "", listener, errorListener, headers);
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (with headers and muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param headers: Added headers
* #param mute: Muted (put it to true, to make sense)
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener, Map<String, String> headers, boolean mute) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, headers);
this.muteRequest = mute;
}
/**
* Method to be called if you want to send some objects to your server via body in JSON of the request (without header and muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param toBeSent: Object which will be transformed in JSON via Gson and sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param mute: Muted (put it to true, to make sense)
*/
public GenericRequest(int method, String url, Class<T> classtype, Object toBeSent,
Response.Listener<T> listener, Response.ErrorListener errorListener, boolean mute) {
this(method, classtype, url, new Gson().toJson(toBeSent), listener,
errorListener, new HashMap<String, String>());
this.muteRequest = mute;
}
/**
* Method to be called if you want to send something to the server but not with a JSON, just with a defined String (without header and not muted)
*
* #param method: HTTP Method
* #param url: URL to be called
* #param classtype: Classtype to parse the JSON returned from the server
* #param requestBody: String to be sent to the server
* #param listener: Listener of the request
* #param errorListener: Error handler of the request
* #param mute: Muted (put it to true, to make sense)
*/
public GenericRequest(int method, String url, Class<T> classtype, String requestBody,
Response.Listener<T> listener, Response.ErrorListener errorListener, boolean mute) {
this(method, classtype, url, requestBody, listener,
errorListener, new HashMap<String, String>());
this.muteRequest = mute;
}
#Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
// The magic of the mute request happens here
if (muteRequest) {
if (response.statusCode >= 200 && response.statusCode <= 299) {
// If the status is correct, we return a success but with a null object, because the server didn't return anything
return Response.success(null, HttpHeaderParser.parseCacheHeaders(response));
}
} else {
try {
// If it's not muted; we just need to create our POJO from the returned JSON and handle correctly the errors
String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
T parsedObject = gson.fromJson(json, clazz);
return Response.success(parsedObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
return null;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
private void configureRequest() {
// Set retry policy
// Add headers, for auth for example
// ...
}
}
It could seem a bit overkill but it's pretty cool to have all these constructors because you have all the cases:
(The main constructor wasn't meant to be used directly although it's, of course, possible).
Request with response parsed to POJO / Headers manually set / POJO to Send
Request with response parsed to POJO / POJO to Send
Request with response parsed to POJO / String to Send
Request with response parsed to POJO (GET)
Request with response parsed to POJO (GET) / Headers manually set
Request with no response (200 - Empty Body) / Headers manually set / POJO to Send
Request with no response (200 - Empty Body) / POJO to Send
Request with no response (200 - Empty Body) / String to Send
Of course, in order that it works, you have to have Google's GSON Lib; just add:
compile 'com.google.code.gson:gson:x.y.z'
to your dependencies (current version is 2.3.1).
final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");
JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);
refer
final String url = "some/url";
instead of:
final JSONObject jsonBody = "{\"type\":\"example\"}";
you can use:
JSONObject jsonBody = new JSONObject();
try {
jsonBody.put("type", "my type");
} catch (JSONException e) {
e.printStackTrace();
}
new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });
You can also send data by overriding getBody() method of JsonObjectRequest class. As shown below.
#Override
public byte[] getBody()
{
JSONObject jsonObject = new JSONObject();
String body = null;
try
{
jsonObject.put("username", "user123");
jsonObject.put("password", "Pass123");
body = jsonObject.toString();
} catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
return body.toString().getBytes("utf-8");
} catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
final Map<String,String> params = new HashMap<String,String>();
params.put("email", customer.getEmail());
params.put("password", customer.getPassword());
String url = Constants.BASE_URL+"login";
doWebRequestPost(url, params);
public void doWebRequestPost(String url, final Map<String,String> json){
getmDialogListener().showDialog();
StringRequest post = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
getmDialogListener().dismissDialog();
response....
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d(App.TAG,error.toString());
getmDialogListener().dismissDialog();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = json;
return map;
}
};
App.getInstance().getRequestQueue().add(post);
}
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
JSONObject JObj = new JSONObject();
try {
JObj.put("Id","1");
JObj.put("Name", "abc");
} catch (Exception e) {
e.printStackTrace();
}
params.put("params", JObj.toString());
// Map.Entry<String,String>
Log.d("Parameter", params.toString());
return params;
}

How to POST Json Array in Json Object using volley in android

I want to send this json body to server using POST METHOD
{"device_type": "SUP","commands": [
{
"command_id": 165,
"arguments": [
{
"name": "Host",
"value": "google.com"
}
]
}]}
I tried many solutions available on web but most of them tell to format the string and sent to server. Is there any correct way to send this body to server end using volley. please help me. Thanks.
Let's start from the bottom. First,
JSONObject json1= new JSONObject();
json1.put("name","Host");
json1.put("value","google.com");
After this we put the above object inside an array
JSONArray jsonArray = new JSONArray();
jsonArray.put(json1);
Now we add the above array and command id to a new object
JSONObject json2= new JSONObject();
json2.put("command_id","165");
json2.put("arguments",jsonArray);
Again this is an object of commands array
JSONArray jsonArray2 = new JSONArray();
jsonArray2.put(json2);
Now we put the above array and device type inta a final object
JSONObject json3= new JSONObject();
json3.put("device_type","SUP");
json3.put("commands",jsonArray2);
Now you can convert json3 object to string and send to server.
json3.toString;
create a JSONObject json = new JSONObject(device_type(in your case)) for the json data you would like and post it to volley
You can use this class:
public class GsonRequest<T> extends Request<T> {
public static final String HEADER_CONTENT_TYPE = "Content-Type";
public static final String CONTENT_TYPE_TEXT_HTML = "text/html";
public static final int HTTP_STATUS_OK = 200;
protected final Type mTypeOfT;
private final Response.Listener<T> mListener;
protected final Gson mGson;
protected String mUrl = "";
protected boolean mIsCached = false;
/**
* Create a new Gson Json-parser request.
*
* #param method the Http method see {#link com.android.volley.Request.Method}
* #param typeOfT type of generic.
* #param url request url.
* #param listener response listener.
* #param errorListener error listener.
*/
public GsonRequest (final int method, final Type typeOfT, final String url,
final Response . Listener < T > listener,
final Response . ErrorListener errorListener) {
this(method, typeOfT, url, listener, errorListener, new Gson ());
}
/**
* Create a new Gson Json-parser request with a custom gson instance (useful for specifying
* custom date formats, etc.)
*
* #param method the Http method see {#link com.android.volley.Request.Method}
* #param typeOfT type of generic.
* #param url request url.
* #param listener response listener.
* #param errorListener error listener.
* #param gson custom Gson instance.
*/
public GsonRequest (final int method, final Type typeOfT, final String url,
final Response . Listener < T > listener,
final Response . ErrorListener errorListener, final Gson gson) {
super(method, url, errorListener);
mListener = listener;
mTypeOfT = typeOfT;
mGson = gson;
mUrl = url;
}
#Override
protected Response < T > parseNetworkResponse (final NetworkResponse response) {
try {
String charset = HttpHeaderParser . parseCharset (response.headers);
Log.d("response", "1");
final String responseData = new String (response.data, charset);
Log.d("response", "2");
logResponse("Request finished with response from the server:", response, responseData);
if (isHtmlFacade(response)) {
return Response.error(new VolleyError ());
}
T responseObject;
if (responseData.startsWith("{\"list\":")) {
Log.d("response", "if");
String json = responseData . substring (responseData.indexOf(":") + 1, responseData.indexOf("]")+1);
responseObject = mGson.fromJson(json, mTypeOfT);
} else {
Log.d("response-single", responseData);
responseObject = mGson.fromJson(responseData, mTypeOfT);
}
return Response.success(responseObject, HttpHeaderParser.parseCacheHeaders(response));
} catch (Exception e) {
return Response.error(new ParseError (e));
}
}
/**
* #param response the response to check
* #return true if the response contains html according to its Content-Type and the status is
* 200 OK.
*/
private boolean isHtmlFacade(NetworkResponse response) {
Map<String, String> headers = response . headers;
String contentType = headers . get (HEADER_CONTENT_TYPE);
return response.statusCode == HTTP_STATUS_OK && contentType != null
&& contentType.contains(CONTENT_TYPE_TEXT_HTML);
}
#Override
protected void deliverResponse(final T response) {
mListener.onResponse(response);
}
}
And then call:
GsonRequest<Model> request = new GsonRequest<Model>(Request.Method.POST,Model.class,"http://requestUrl", onsuccessListener, onerrorListener)

GET Request parameters using Volley

I'm making an Android App that integrates with the Facebook API and uses a REST API, so I'm using Volley. However, I'm trying to issue a GET request for a JSON Array, and have to include the Facebook Authorization token in order to access the server. Most of the questions I've seen on this are relatively old, and it seems like Volley now provides support to pass in request params (from the volley github page):
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONArray} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public JsonArrayRequest(int method, String url, JSONArray jsonRequest,
Listener<JSONArray> listener, ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
But when I make and issue a JsonArrayRequest, I get a com.android.volley.AuthFailureError. Here is my code, does anyone know what I'm doing wrong?
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println("Yo im here");
JSONObject requestParams = new JSONObject();
JSONArray paramArray = new JSONArray();
try {
requestParams.put("Authorization", "JWT (Facebook auth token)");
paramArray.put(requestParams);
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println(paramArray.toString());
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET,
GET_MAP_MICS,
paramArray,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray micArray) {
try {
for (int i = 0; i < micArray.length(); i++) {
JSONObject jsonobject = micArray.getJSONObject(i);
int micId = jsonobject.getInt("micId");
String status = jsonobject.getString("status");
System.out.println("Good so far!");
double venLat = jsonobject.getDouble("venueLat");
double venLong = jsonobject.getDouble("venueLat");
System.out.println("got here, check it: " + venLat);
}
}catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError e) {
System.out.println(e);
}
});
GET method don't take parameters only POSTwill
in your case your passing Headers as body for GET method you have pass headers
JsonObjectRequest request = new JsonObjectRequest(url, (JSONObject) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject jsonObject) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> map = new HashMap<>();
/*Add your headers here*/
return super.getHeaders();
}
};
final possibility there is two same class name will be there in your project for example any lib your using also using volley lib this happens once for me

Send ByteArray with Android volley

There is any way to send a byte array with Volley?
Now I'm using this:
post.setEntity(new ByteArrayEntity(rawPacket.toByteArray()));
try {
response = client.execute(post);
} catch (IOException e) {
e.printStackTrace();
}
There is something like this in Volley? There is a method to pass custom object to send with the POST/GET request?
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> params = new HashMap<>();
params.put("RawPacket", rawPacket.toByteArray().toString());
return params;
}
I need something like protected Map<String, ByteArray> getParams()
I find the solution overriding the function public byte[] getBody() to send custom data, I should read better the documentation!
StringRequest stringRequest = new StringRequest(Request.Method.POST, "https://www.example.com/",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public byte[] getBody() throws AuthFailureError {
return new byte[] {1, 2, 3, 4, 5};
}
See code below:
public class JsonArrayRequest extends JsonRequest<JSONArray> {
/**
* Creates a new request.
* #param url URL to fetch the JSON from
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public JsonArrayRequest(String url, Listener<JSONArray> listener, ErrorListener errorListener) {
super(Method.GET, url, null, listener, errorListener);
}
You have to create a subclass of JsonRequest and use that instead.
See related link:
Volley - Sending a POST request using JSONArrayRequest
Also might want to Base64 encode the bytes and add it to the JsonArray.

Android multipart request

I am using Volley lib and I want make an multipart request with string params
I found this code
/**
* MultipartRequest - To handle the large file uploads.
* Extended from JSONRequest. You might want to change to StringRequest based on your response type.
* #author Mani Selvaraj
*
*/
public class MultiPartRequest extends JsonRequest<JSONObject> {
/* To hold the parameter name and the File to upload */
private Map<String,File> fileUploads = new HashMap<String,File>();
/* To hold the parameter name and the string content to upload */
private Map<String,String> stringUploads = new HashMap<String,String>();
private Map<String, String> headers = new HashMap<String, String>();
/**
* Creates a new request.
* #param method the HTTP method to use
* #param url URL to fetch the JSON from
* #param jsonRequest A {#link JSONObject} to post with the request. Null is allowed and
* indicates no parameters will be posted along with request.
* #param listener Listener to receive the JSON response
* #param errorListener Error listener, or null to ignore errors.
*/
public MultiPartRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener, Response.ErrorListener errorListener) {
super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
errorListener);
}
/**
* Constructor which defaults to <code>GET</code> if <code>jsonRequest</code> is
* <code>null</code>, <code>POST</code> otherwise.
*
* #see #JsonObjectRequest(int, String, JSONObject, Listener, ErrorListener)
*/
public MultiPartRequest(String url, JSONObject jsonRequest, Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
this(jsonRequest == null ? Method.GET : Method.POST, url, jsonRequest,
listener, errorListener);
}
public void addFileUpload(String param,File file) {
fileUploads.put(param,file);
}
public void addStringUpload(String param,String content) {
stringUploads.put(param,content);
}
public Map<String,File> getFileUploads() {
return fileUploads;
}
public Map<String,String> getStringUploads() {
return stringUploads;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers;
}
public void setHeader(String title, String content) {
headers.put(title, content);
}
#Override
protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
try {
String jsonString =
new String(response.data, HttpHeaderParser.parseCharset(response.headers));
return Response.success(new JSONObject(jsonString),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JSONException je) {
return Response.error(new ParseError(je));
}
}
}
Is this is a right approach?
RequestQueue queue = MyVolley.getRequestQueue();
MultiPartRequest multiPartRequest = new MultiPartRequest(url,null,new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
}
},new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
multiPartRequest.addFileUpload("logo",file);
multiPartRequest.addStringUpload("firsName","John");
queue.add(multiPartRequest);
But one thing I can't understand how could I use this code for sending file and other params.
As mentioned in a class JsonReqest is post params that can be null. But I couldn't understand how could I use this. Please could anyone tell me how could I do this?

Categories

Resources