Android Volley: POST request - req.body inside of

2020-03-26 11:59发布

I know its been discussed like a billion times, and I have read a couple of questions/answers and this one in particular seemed like a good example -> example. So now I have tried to recreate the code and added my getParams() as well as my getHeaders(). Awkwardly I get a HTTP Status Code 400:

E/Volley: [303] BasicNetwork.performRequest: Unexpected response code 400 for http://10.0.2.2:3000/classes

Since I have created the REST API I can see where this status code 400 comes from, its my NodeJS response if the req.body doesn't contain mAtt, mDatum, mRID, mVon. So now I know that my POST request is not properly working even tho I set my getParams()as well as my getHeaders() ...

Now, my guess would be that I'm setting Params but I'm fetching req.body.mAtt, req.body.mDatum , req.body.mRID, req.body.mVon, that would explain why my NodeJS returns the status code 400. If I fetched req.query.mAtt I would probably get something back?

Is there a certain method that need to be overridden by me, to actually set the body instead of the query params?

This is what my POST req looks like:

    JsonObjectRequest JOPR = new JsonObjectRequest(Request.Method.POST,
                       myAcitveLessonPOSTUrl, null, 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());
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }

        @Override
        protected Map<String, String> getParams()
        {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("mAtt", "+1");
            params.put("mDatum", mDatum);
            params.put("mRID", mRID);
            params.put("mVon", mVon);

            return params;
        }


    };


    requestQ.add(JOPR);

Thank you!

1条回答
Emotional °昔
2楼-- · 2020-03-26 12:53

I finally got it. I continued to search for answers and stumbled upon this question/answer link.

Since my REST API is looking for req.body variables, the getParams() have no effect. In order to send req.body variables the getBody() method has to be overridden.

So what I basically had to do was:

1) create a JSONObject

2) put my key:values inside the JSONObject

3) get the contents of my JSONObject into a String via toString()

4) @Override the getBody() method inside my JsonObjectRequest

Done.

So my corrected code looks like this:

    JSONObject jsonBodyObj = new JSONObject();
    try{
        jsonBodyObj.put("mAtt", "+1");
        jsonBodyObj.put("mDatum",mDatum);
        jsonBodyObj.put("mRID",mRID);
        jsonBodyObj.put("mVon",mVon);
    }catch (JSONException e){
        e.printStackTrace();
    }
    final String requestBody = jsonBodyObj.toString();

    JsonObjectRequest JOPR = new JsonObjectRequest(Request.Method.POST,
                   myAcitveLessonPOSTUrl, null, new Response.Listener<JSONObject>(){
        @Override
        public void onResponse(JSONObject response) {
            try {
                VolleyLog.v("Response:%n %s", response.toString(4));
                populateLessonDetails(myActiveLessonURLFiltered);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    }){
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();
            headers.put("Content-Type", "application/json");
            return headers;
        }


        @Override
        public byte[] getBody() {
            try {
                return requestBody == null ? null : requestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
        VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
                        requestBody, "utf-8");
                return null;
            }
        }


    };

    requestQ.add(JOPR);  

Kudos to @dvdciri for his original question and Edits, what would eventually become this answer!

查看更多
登录 后发表回答