0

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

andrewb
  • 2,995
  • 7
  • 54
  • 95
  • Is the Title and Message supposed to be in the body and not in header? Also you're returning null in the Body. – Enzokie Feb 07 '17 at 02:20
  • I think title and message should be in the body - what is the purpose of getBody? I have put this together from multiple places online – andrewb Feb 07 '17 at 02:21
  • Don't use `getBody`. You have JSON. Volley has JSON classes. http://afzaln.com/volley/com/android/volley/toolbox/JsonObjectRequest.html – OneCricketeer Feb 07 '17 at 02:22
  • Anyway, you have a 500 Error, so what is your server saying is wrong? – OneCricketeer Feb 07 '17 at 02:23
  • @andrewb May I see a screenshot on how you do a request in postman? just hide your URL for safety. – Enzokie Feb 07 '17 at 02:24
  • I added it @Enzokie – andrewb Feb 07 '17 at 02:36
  • As @cricket_007 metioned above, if your server responses error message, try checking it http://stackoverflow.com/questions/35841118/how-to-get-error-message-description-using-volley. One more thing, does your volley request need any header or not (In Postman screenshot, I have found headers section having 1 value) – BNK Feb 07 '17 at 03:02
  • The header in Postman is the content-type, but I presume if I use the JsonObjectRequest class the content type is set to application/json? – andrewb Feb 07 '17 at 03:17

2 Answers2

2

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);
Enzokie
  • 7,365
  • 6
  • 33
  • 39
1
String webAddress = "http://example.com/api/helprequests/";
 RequestQueue queue = Volley.newRequestQueue(this);

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

RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
        JsonObjectRequestWithHeader jsonObjReq = new JsonObjectRequestWithHeader(Request.Method.POST,
                webAddress , jsonObject, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                Log.v("Response0", response.toString());
}
}, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d("Response", "Error: " + error.getMessage());
                pd.dismiss();

            }
        });
        int socketTimeout = 50000;//30 seconds - change to what you want
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        jsonObjReq.setRetryPolicy(policy);
        queue.add(jsonObjReq);
        return null;
    }
  • While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. – S.R Jun 12 '17 at 06:45