Android使用Volley发送JSON原始数据的POST请求

4

我需要使用voley发送post请求,但是当我尝试按照要求发送原始数据时,我得到了以下错误信息:

******com.android.volley.ServerError******: {"message":"No user account data for registration received."}

在postman中我尝试了同样的操作,它可以正常工作,那么我该如何在我的代码中修复这个问题呢?

以下是在postman中可以正常工作的原始数据 ->

    {
    "camp1": {
        "value": "value"
    },
    "camp2": {
        "value": "value2"
    }
}

这是我的代码中的内容 ->
    public void requestRegistrationInfo(@NonNull final String camp1, @NonNull final String camp2,final Listener listener) {
            RequestQueue requestQueue = Volley.newRequestQueue(context);
            requestQueue.add(new JsonObjectRequest(
                    Request.Method.POST, URL,
                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.v("IT WORK");
                            listener.onSuccess();
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Log.e("******" + error.toString() + "******", getErrorMessage(error));
                            listener.onFailure();
                        }
                    })
{

                @Override
                protected Map<String,String> getParams() {

                    Map<String, String> map = new HashMap<>();
                    map.put("{camp1", "value");
                    map.put("camp2", "value");

                    return map;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> map = new HashMap<>();
                    map.put("header1", "header1");
                    map.put("header2", "header2");
                    return map;
                }
            });
        }

我该怎么做才能正确发送原始的JSON数据而不显示错误?

4个回答

3

通常情况下,JSONObject请求不会触发getParams()方法,该方法仅适用于String请求和传递键值对数据负载。如果您想传递带有JSON数据的原始正文,则首先必须将数据格式化为服务器可接受的格式。在您的情况下,这是您的数据。

{
  "camp1":{
   "value":"value1"
  },
  "camp2":{
    "value2":"value2"
  }
}

您需要将数据转换为服务器可接受的JSON格式,如下所示。
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("value", "value1");
                JSONObject jsonObject1 = new JSONObject();
                jsonObject1.put("value2", "value2");
                JSONObject jsonObject2 = new JSONObject();
                jsonObject2.put("camp1", jsonObject);
                jsonObject2.put("camp2",jsonObject1);

 //jsonObject2 is the payload to server here you can use JsonObjectRequest 

 String url="your custom url";

 JsonObjectRequest jsonObjectRequest = new JsonObjectRequest
                        (Request.Method.POST,url, jsonObject2, new com.android.volley.Response.Listener<JSONObject>() {

                            @Override
                            public void onResponse(JSONObject response) {

                                try {
                                   //TODO: Handle your response here
                                }
                                catch (Exception e){
                                    e.printStackTrace();
                                }
                                System.out.print(response);

                            }
                        }, new com.android.volley.Response.ErrorListener() {

                            @Override
                            public void onErrorResponse(VolleyError error) {
                                // TODO: Handle error
                                error.printStackTrace();

                            }


                        });

在url参数之后,JsonObjectRequest构造函数将接受json格式的有效负载,并将数据传递给它。


0
如果您调用任何REST-API,请注意它的负载始终以JSON格式存在。因此,您可以像这样使用对象主体作为有效载荷。
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", input_loginId.getText().toString());
params.put("password", input_password.getText().toString());

你可以像这样将它传递给方法

JsonObjectRequest logInAPIRequest = new JsonObjectRequest(Request.Method.POST, YOUR-URL,
                         new JSONObject(params), new Response.Listener<JSONObject>() {
 @Override
                     public void onResponse(JSONObject response) {    
                         input_errorText.setText(response.toString());
                     }
                 }, new Response.ErrorListener() {
                     @Override
                     public void onErrorResponse(VolleyError error) {
                         input_errorText.setText("Error: " + error.getMessage());
                     }
                 });

0
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley Demo");
jsonBody.put("Author", "BNK");
final String requestBody = jsonBody.toString();

StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.i("VOLLEY", response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("VOLLEY", error.toString());
    }
}) {
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

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

    @Override
    protected Response<String> parseNetworkResponse(NetworkResponse response) {
        String responseString = "";
        if (response != null) {
            responseString = String.valueOf(response.statusCode);
            // can get more details such as response.headers
        }
        return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
    }
};

requestQueue.add(stringRequest);
} catch (JSONException e) {
 e.printStackTrace();
}

请检查已编辑的getBody()函数。
   @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return requestBody == null ? null : encodeParameters(requestBody , getParamsEncoding());
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", requestBody, "utf-8");
            return null;
        }
    }

使用这段代码时,出现了错误 -> com.android.volley.ServerError: {"message":"不可接受的格式:json"} - Liru
我正在尝试这个,encodeParameters是自定义函数吗? - Mahen

0

这是测试过的代码,请尝试:

 private void multipartRequestWithVolly() {
        String urll = "your_url";

        progressDialog.show();
        StringRequest request = new StringRequest(Request.Method.POST, urll, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressDialog.dismiss();
                if (!TextUtils.isEmpty(response)) {
                    Log.e(TAG, "onResponse: " + response);
                    textView.setText(response);
                } else {
                    Log.e(TAG, "Response is null");
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                progressDialog.dismiss();
                Log.e(TAG, "onErrorResponse: " + error.toString());
            }
        }) {

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                hashMap = new HashMap<>();
                hashMap.put("OPERATIONNAME", "bplan");
                hashMap.put("mcode", "298225816992");
                hashMap.put("deviceid", "dfb462ac78317846");
                hashMap.put("loginip", "192.168.1.101");
                hashMap.put("operatorid", "AT");
                hashMap.put("circleid", "19");
                return hashMap;
            }
        };
        AppController.getInstance().addToRequestQueue(request);
    }

使用这段代码,会出现与下面代码相同的错误 -> com.android.volley.ServerError: {"message":"不可接受的格式:json"} - Liru

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接