Volley Request with Raw data

2019-02-21 01:24发布

In my application I have to send POST request with JSON req param, I tried to create request with Postman Rest Client and it is working fine but not working with below code.

In Postman req parameter sent as raw data, But I am not sure how to send it with Volley request.

public Request getHTTPPostReqResponse(String URL, Class mClass, final Map<String, String> params, final String contentType, final String body) {
    mResponseListener.requestStarted();

    Request mRequest = new GsonRequest(Request.Method.POST, URL, mClass, new Response.Listener<Object>() {

        @Override
        public void onResponse(Object response) {
            mResponseListener.requestCompleted(response);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            mResponseListener.requestEndedWithError(error);
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            return params;
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            if (TextUtils.isEmpty(body)){
                return super.getBody();
            }else {
                return  body.getBytes();
            }
        }

        @Override
        public String getBodyContentType() {
            return contentType;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<>();
            params.put("Content-Type", contentType);
            return params;
        }
    };

    mRequest.setRetryPolicy(new DefaultRetryPolicy(
            MY_SOCKET_TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    return mRequest;
}

Request Parameter:

{
    "nodeId": null,
    "userId": null,
    "mobileNumber": "993000008",
    "emailId": "sharma@gmail.com",
    "userProfile": null,
    "region": null,
    "countryCode": "91",
    "password": "pass@123",
    "places": [],
    "trustedNetwork": [],
    "profilePic": null,
    "fullName": null,
    "longitude": 0.0,
    "latitude": 0.0
}

2条回答
放我归山
2楼-- · 2019-02-21 01:50

This is the working code, you can try. we can use JsonObjectRequest for raw data. Here i have just showing how to make requestObject that is added in queue

String url = MConstant.API_END+"/userLogin";
    Map<String, String> params = new HashMap<String, String>();
    params.put("email",mEmailView.getText().toString());
    params.put("password",mPasswordView.getText().toString());
    params.put("api",MConstant.API);
    JSONObject objRegData = new JSONObject(params);
    JsonObjectRequest jsObjRequest = new JsonObjectRequest
            (Request.Method.POST, url, objRegData, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    try {

                        // handle response data
                    } catch (JSONException e) {
                        e.printStackTrace();
                        //pDialog.show();
                    }

                }
            }, new Response.ErrorListener() {


                @Override
                public void onErrorResponse(VolleyError error) {
                    pDialog.hide();
                }
            })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("Content-Type", "application/json");
            return params;
        }
    };

in server side PHP we can get data using

$json = file_get_contents('php://input');
$myPostData = json_decode($json, true);
查看更多
Juvenile、少年°
3楼-- · 2019-02-21 02:03

hope this isn't too late.

Have you tried a different type of request, like String or JsonObject? And a different syntax for the params?

e.g.

     Map<String, Object> jsonParams = new ArrayMap<>();
    jsonParams.put("nodeId", null);
    jsonParams.put("userId", null);
    jsonParams.put("mobileNumber", "sharma@gmail.com");
    jsonParams.put("userProfile", null);
    jsonParams.put("region", null);
    jsonParams.put("countryCode", 91);
    jsonParams.put("password", pass@123);
    jsonParams.put("places", new ArrayList());
    jsonParams.put("trustedNetwork", new ArrayList());
    jsonParams.put("profilePic", null);
    jsonParams.put("fullName", null);
    jsonParams.put("longitude", 0.0);
    jsonParams.put("latitude", 0.0);

    JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(jsonParams),
            new Response.Listener<JSONObject>()
            {
                @Override
                public void onResponse(JSONObject response)
                {
                  mResponseListener.requestCompleted(response);
                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                    if (null != error.networkResponse)
                    {
                     mResponseListener.requestEndedWithError(error);
                    }
                }
            });

Also, have a look at this SO question. Hope any of this helps.

查看更多
登录 后发表回答