【问题标题】:Trying to post to a custom API, receiving volley.ClientError尝试发布到自定义 API,收到 volley.ClientError
【发布时间】:2020-06-14 23:01:24
【问题描述】:

我正在尝试使用 volley 将一些数据发布到自定义 API。这也是我正在尝试更新信息的 API 模型。可以在以下 POST 链接下的 http://ecoproduce.eu/swagger/index.html 上找到它:http://ecoproduce.eu/api/User/register/

{
  "firstName": "string",
  "lastName": "string",
  "email": "string",
  "password": "string",
  "zipCode": 0,
  "state": 0,
  "account": 0
}

当我尝试向 API 添加新的测试用户时,我收到以下错误:

E/Volley: [9583] BasicNetwork.performRequest: Unexpected response code 400 for http://ecoproduce.eu/api/User/register/
E/Error response: com.android.volley.ClientError

这是我用来 POST 用户的函数。

private void addUser() {

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    JsonArrayRequest arrayRequest = new JsonArrayRequest(
            Request.Method.POST,
            "http://ecoproduce.eu/api/User/register/",
            null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e("Error response", error.toString());
                }
            })

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

                    Map<String,String> params = new HashMap<String,String>();
                    params.put("firstName", "Vasko");
                    params.put("lastName", "Vasilev");
                    params.put("email", "vasko@hotmail.com");
                    params.put("password", "18yoBonev");
                    params.put("zipCode", "0");
                    params.put("state", "1");
                    params.put("account", "2");

                    return params;
                }

                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    headers.put("Content-Type", "application/json; charset=utf-8");
                    return headers;
                }

            };

    requestQueue.add(arrayRequest);

}

我已经尝试寻找解决方案,但我找不到任何有用的东西。是否会发生错误,因为我试图将邮政编码、状态和帐户作为字符串传递,即使它们是模型中的整数?如果是这样,我怎样才能将它们作为整数传递?目前我正在覆盖必须返回 Map 实例的 getParams() 函数。如果这个问题有一个简单的解决方案,我想提前道歉,这是我第一次使用 RESTful API。

【问题讨论】:

  • 帖子是 JSONObject 所以尝试使用JsonObjectRequest 而不是JsonArrayRequest

标签: java android rest android-volley


【解决方案1】:

通过使用字符串请求解决。找到答案:How to send a POST request using volley with string body?

代码目前是这样的:

 private void addUser() {

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();

    try {
        jsonObject.put("firstName", "Vasko");
        jsonObject.put("lastName", "Vasilev");
        jsonObject.put("email", "vaskovaskovasko@hotmail.com");
        jsonObject.put("password", "18yoBonev");
        jsonObject.put("zipCode", 0);
        jsonObject.put("state", 1);
        jsonObject.put("account", 2);

        jsonArray.put(jsonObject);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    final String requestBody = jsonObject.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://ecoproduce.eu/api/User/register", 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() {
            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;
            }
        }

        @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);
}

【讨论】:

    【解决方案2】:

    Volley 不适用于 https 请求,也许此链接对您有帮助:Volley with Https

    如果您想授权 Http 纯文本,请将此行 android:usesCleartextTraffic="true" 添加到您的清单中。

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2021-08-05
      • 2017-12-31
      • 1970-01-01
      • 2020-02-09
      • 2020-04-06
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      相关资源
      最近更新 更多