首页 > 解决方案 > 带有 JSON 的 Volley Post - 获取 422 状态代码

问题描述

我正在尝试使用Volley将 JSON 对象发送到使用 MongoDB 的 Loopback 应用程序 API。我可以看到数据已成功保存在数据库中。但是 Volley 响应总是显示状态码是422。有人可以指出我做错了什么吗?

这是错误消息:

BasicNetwork.performRequest: Unexpected response code 422 for http://localhost:3001/api/Persons

这是我要发送的 JSON:

{
  "map_coordinates": {
    "lat": xxxxxx,
    "lng": xxxxxxx
  },
  "first_name": "xxxxx",
  "middle_name": "",
  "family_name": "xxxxxx",
  "gender": "xxxxxx",
  "role": "xxxxxx",
  "dob": "2017-09-28T05:51:40.836Z",
  "picture_of_person": "",
  "username": "ajxxxx7@gmail.com",
  "deviceToken": "xxxxxxxx",
  "portal_address": "xxxxx",
  "email": "ajxxxxx7@gmail.com",
  "password": "xxxxxxx",
  "vcode": 562991,
  "mobile": "+91xxxxxxxx"
}

我不认为 JSON 有问题,因为如果我从 Loopback 资源管理器 POST 相同的对象,那么请求会成功通过并返回状态码 200。

这是我用来发送 JSON 请求的代码。

public void postJsonRequest(String url, JSONObject data, final Callback<JSONObject, VolleyError> callback) {
    JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.POST,
            url, data, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            callback.onSuccess(response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            callback.onFailure(error);
        }
    });
    makeJsonRequest(objectRequest);
}

private void makeJsonRequest(JsonObjectRequest request) {
    RequestQueue queue = Volley.newRequestQueue(EngageMyTime.getInstance().getEMTContext());
    queue.add(request);
}

任何帮助/想法将不胜感激。

标签: javaandroidjsonandroid-volleyloopbackjs

解决方案


尝试在服务器端设置默认字符集 UTF-8,并在发送前以 UTF-8 编码 json 数据

在安卓中

URLEncoder.encode(string,"UTF-8");

推荐阅读