【问题标题】:Getting volley client error on post request在发布请求时收到截击客户端错误
【发布时间】:2021-09-23 23:49:39
【问题描述】:

我正在尝试使用 volley 将数据传递给 api,如下所示

    RequestQueue requestQueue = Volley.newRequestQueue(context);

    Map<String, String> params = new HashMap();
    params.put("fullName","some name");
    params.put("phone","some phone number");
    JSONObject parameters = new JSONObject(params);

    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url,parameters, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            Log.d("jdjd","response = "+response);
        }
    }
            , new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("jdjd","response_error = "+error);
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String>  params = new HashMap<String, String>();
            params.put("api-key", "my_api_key");
            return params;
        }
    };
    requestQueue.add(jsonObjectRequest);

我也试过

params.put("Content-Type", "application/json; charset=utf-8");

然后添加

        @Override
        public String getBodyContentType() {
            return "application/json";
        }

任何帮助将不胜感激

【问题讨论】:

    标签: android android-volley


    【解决方案1】:
           StringRequest request=new StringRequest(Request.Method.POST, "url", new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
        
                        Log.e("TAG", "onResponse: "+response );
        
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
        
                    }
                }){
        
                    @Override
                    protected Map<String, String> getParams()  {
    //put your all parameter here
                        HashMap<String,String> hashMap =new HashMap<>();
                        hashMap.put("pair_id","1");
                        hashMap.put("pair_symbol","BTC_USDT");
                        return hashMap;
                    }
                };
                Volley.newRequestQueue(getContext()).add(request);
    

    试试这个

    【讨论】:

    • 但是API返回的是json对象,那么如何将响应字符串转换为json对象呢?
    • 尝试 { JSONObject object =new JSONObject(response); } catch (JSONException e) { e.printStackTrace(); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    相关资源
    最近更新 更多