Pass Parameter with Volley POST

后端 未结 3 1956
旧巷少年郎
旧巷少年郎 2020-12-01 11:41

I was able to call an HTTP endpoint using Postman and these parameters:

{
    \"name\":\"Val\",
    \"subject\":\"Test\"
}

However I am una

相关标签:
3条回答
  • 2020-12-01 12:02

    The server code is expecting a JSON object is returning string or rather Json string.

    JsonObjectRequest

    JSONRequest sends a JSON object in the request body and expects a JSON object in the response. Since the server returns a string it ends up throwing ParseError

    StringRequest

    StringRequest sends a request with body type x-www-form-urlencoded but since the server is expecting a JSON object. You end up getting 400 Bad Request

    The Solution

    The Solution is to change the content-type in the string request to JSON and also pass a JSON object in the body. Since it already expects a string you response you are good there. Code for that should be as follows.

    StringRequest sr = new StringRequest(Request.Method.POST, Constants.CLOUD_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            mView.showMessage(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            mView.showMessage(error.getMessage());
        }
    }) {
        @Override
        public byte[] getBody() throws AuthFailureError {
            HashMap<String, String> params2 = new HashMap<String, String>();
            params2.put("name", "Val");
            params2.put("subject", "Test Subject");
            return new JSONObject(params2).toString().getBytes();
        }
    
        @Override
        public String getBodyContentType() {
            return "application/json";
        }
    };
    

    Also there is a bug here in the server code

    var responseMessage = $"Hello {personToGreet}!";
    

    Should be

    var responseMessage = $"Hello {name}!";
    
    0 讨论(0)
  • 2020-12-01 12:02

    Add the content type in the header

    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put("Content-Type", "application/json; charset=utf-8");
    return headers;
    }    
    
    0 讨论(0)
  • 2020-12-01 12:05

    You are using params.put instead of params2.put in your hash map while passing parameters. because your object name is params2

    0 讨论(0)
提交回复
热议问题