How can i send string array through volley? - android

I have to send a json like this:
{
"user_id": "5750891ffe77d2d41732d535",
"categories" :["5751cd8cb61c39200b368cf3","575b35b9c456c8751cd8530f", "575b35c5c456c8751cd85313"]
}
but volley only send strings, not an array. This is my request class, i'm using the volley StringRequest but i think there is a way to send also an array:
public class VolleyRequest extends StringRequest {
private Map<String, String> params;
Context context;
public VolleyRequest(int method, final Context context, String url, Map<String, String> params, final Response.Listener<String> listener) {
super(method, url, listener, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("WS", volleyError.toString());
}
});
setRetryPolicy(new DefaultRetryPolicy(10000, 10, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
this.params = params;
this.context = context;
}
#Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=UTF-8";
}
#Override
public Map<String, String> getParams() throws AuthFailureError {
return this.params;
}
}

I figure it out! you have to override the getBody() function, create a custom encodeParameters function and also override getBodyContentType() changing it to return "application/json".
public class VolleyRequest extends StringRequest {
private Map<String, String> params;
Context context;
public VolleyRequest(int method, final Context context, String url, String json, final Response.Listener<String> listener) {
super(method, url, listener, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.d("WS", volleyError.toString());
}
});
setRetryPolicy(new DefaultRetryPolicy(10000, 10, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
this.params = params;
this.context = context;
}
#Override
public byte[] getBody() throws AuthFailureError {
return encodeParameters(getParamsEncoding());
}
private byte[] encodeParameters(String paramsEncoding) {
try {
if(json!=null) {
return json.getBytes(paramsEncoding);
}
else return null;
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
}
#Override
public String getBodyContentType() {
return "application/json";
}
#Override
public Map<String, String> getParams() throws AuthFailureError {
return this.params;
}
}
Look that now i pass a String json as parameter on my request, not a HashMap. To create that string a used Gson and a Model of my wanted json body:
public class ModelSendFilters {
String user_id;
String[] categories;
public String getUser_id() {return user_id;}
public void setUser_id(String user_id) {this.user_id = user_id;}
public String[] getCategories() {return categories;}
public void setCategories(String[] categories) {this.categories = categories;}
}
To create the String json:
new Gson().toJson(user, ModelSendFilters.class)

Related

Custom Gson request and response in post method

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.

Android volley implementing custom request with getParams that accepts JSONArray param

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();

how to make post call with custom object using volley in android

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().

Volley Post GSON Request Issue

I have created the volley custom post GSon request, but i am unable to call it.
GSON POST Request:
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 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 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.params = null;
}
/**
* Make a POST 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
*/
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.params = params;
this.listener = listener;
this.headers = null;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
#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));
}
}
}
**Response Generic Model Classes: **
public class BaseResponse<T> implements Serializable {
private boolean response;
private String message;
private String status;
private String userStatus;
private String token;
private T data;
public boolean isResponse() {
return response;
}
public void setResponse(boolean response) {
this.response = response;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getStatus() {
return status;
}
public String getUserStatus() {
return userStatus;
}
public String getToken() {
return token;
}
}
Data Model Class:
public class OTPCode implements Serializable {
private String code;
#SerializedName("mobile")
private String phone;
#SerializedName("id")
private String userId;
private String name;
private String email;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
Below is Callback which showing error :
GsonRequest<BaseResponse<OTPCode>> baseResponseGsonRequest = new GsonRequest<BaseResponse<OTPCode>>
(Request.Method.POST,url,BaseResponse<OTPCode>.class, params, new Response.Listener<BaseResponse<OTPCode>>() {
#Override
public void onResponse(BaseResponse<OTPCode> response) {
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
I am parsing BaseResponse.class to GsonRequest but its
showing me error. I might doing some mistake. Please help!!
As BaseResponse is generic class, .class will not work, use Type for that
Type baseResponseType=new TypeToken<>(){}.getType();

Android Volley Request with Body

Is it possible to send a simple text in the body of a StringRequest using DELETE-Method?
I couldn't find any example where somebody put something in the body of a request...
This is my request and I want to add "{'deviceid':'xyz'}" to the body (method is DELETE):
final StringRequest stringRequest = new StringRequest(method, url + "?token=" + token, new Response.Listener<String>() {
#Override
public void onResponse(String jsonResponse) {
// do something
}, new Response.ErrorListener() {
// do something
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("api-version", "1");
return headers;
}
};
This because Volley doesn't send the Body for DELETE by default. Only for POST, PUT and PATCH. Unfortunate to say the least
There is a workaround for it listed here: Volley - how to send DELETE request parameters?
Try this:
public class StringJSONBodyReqest extends StringRequest {
private static final String TAG = StringJSONBodyReqest.class.getName();
private final String mContent;
public StringJSONBodyReqest(int method, String url, String content, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
mContent = content;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("api-version", "1");
return headers;
}
#Override
public byte[] getBody() throws AuthFailureError {
byte[] body = new byte[0];
try {
body = mContent.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Unable to gets bytes from JSON", e.fillInStackTrace());
}
return body;
}
#Override
public String getBodyContentType() {
return "application/json";
}
}
mContent is your json String
StringRequest stringRequest = new StringRequest(StringRequest.Method.PUT,
BASE_URL + "/addItem",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//handle error
}
}) {
#Override
public byte[] getBody(){
String jsonString = json to send;
return jsonString.getBytes();
}
#Override
public String getBodyContentType() {
return "application/json";
}
};
MyRequestQueue.getInstance().addRequest(stringRequest);

Categories

Resources