andrewb andrewb - 4 years ago 173
JSON Question

Using volley to make web service call

I have a web api setup and one of the endpoints in the API takes a JSON object (which in the API gets resolved to a .NET object).

Using Postman I can successfully call the post endpoint, here is the URL

https://example.com/api/helprequests


And here is the JSON which I include in the Postman request

{"Title":"Test Title", "Message":"Test Message"}


Everything works well in Postman, but I am trying to call this API from an Android app using Volley.

Here is the relevant code

String webAddress = "http://example.com/api/helprequests/";
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.POST, webAddress,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("RESPONSE", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("RESPONSE", "That didn't work!");
}
}) {
@Override
public String getBodyContentType() {
return "application/json";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
Map<String, String> params = new HashMap<String, String>();
params.put("Title","Test title");
params.put("Message", "Test message");
} catch (Exception ex) {
VolleyLog.wtf("Unsupported Encoding");
return null;
}
return null;
}
};
queue.add(stringRequest);


When I run this I get the following error:

E/Volley: [50225] BasicNetwork.performRequest: Unexpected response code 500 for https://example.com/api/helprequests


How do I add post data to a Volley request?

Postman image

Answer Source

Instead of using the StringRequest do use JsonObjectRequest.

 String webAddress = "http://example.com/api/helprequests/";
 RequestQueue queue = Volley.newRequestQueue(this);

 JSONObject object = new JSONObject();
 try {
     object.put("Title", "my title");
     object.put("Message", "my message");
 } catch (JSONException e) {
 }

 JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, webAddress,object, new Response.Listener<JSONObject>() {

     @Override
     public void onResponse(JSONObject object) {
         Log.d("RESPONSE", object.toString());
     }

 }, new Response.ErrorListener() {

     @Override
     public void onErrorResponse(VolleyError volleyError) {
         Log.d("RESPONSE", "That didn't work!");
     }

 });
 queue.add(request);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download