Android发送带有齐射

时间:2017-04-03 12:31:25

标签: android json post android-volley

我必须发送一个voley的帖子,但是当我尝试按照要求发送原始主体时,而不是响应时出现此错误

  

****** com.android.volley.ServerError ******:{" message":"没有收到注册的用户帐户数据。"}

我在邮递员中尝试了同样的方法并且它完美无缺,我如何在我的代码中修复它?

在邮递员工作的原始身体 - >

    {
    "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 个答案:

答案 0 :(得分: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;
        }
    }

答案 1 :(得分: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);
    }

答案 2 :(得分:0)

通常情况下,JSONObject请求没有命中getParams()方法,该方法仅适用于String请求和传递键值对数据有效负载。如果要使用JSON数据传递原始内容,则首先必须将数据格式化为服务器接受的格式。 您的情况就是您的数据

ImageView image = (ImageView) findViewById(R.id.image);

Drawable arrow = getResources().getDrawable(R.drawable.ic_right_arrow);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    if (arrow != null) {
           arrow.setAutoMirrored(true);
    }
}

image.setImageDrawable(arrow);

您必须像这样将数据转换为服务器接受的JSON格式

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

在url参数传递数据之后,JsonObjectRequest将在其构造函数中将有效负载作为json接受

答案 3 :(得分: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());
                     }
                 });