【问题标题】:How to use volley in post request?如何在 post 请求中使用 volley?
【发布时间】:2019-05-29 23:06:04
【问题描述】:

我是 android studio 的新手,我将使用 volley 库从服务器获取数据。

json 请求如下:

{
  "method": "authenticate",
  "params": [
    "dummyuser",
    "dummy"
  ],
  "id": "1",
  "jsonrpc": "2.0"
}

以下是我的代码

RequestQueue requestQueueV1= Volley.newRequestQueue(getApplicationContext());
StringRequest stringRequestV1 = new StringRequest(Request.Method.POST, server_url + AppConfig.VERSION1_URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
            // response is JSONObject
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Toast.makeText(SettingsActivity.this, "Error occurred.", Toast.LENGTH_LONG).show();
    }
}) {
     @Override
     protected Map<String, String> getParams() {
         Map<String, String> request_body = new HashMap<String, String>();
         request_body.put("method", "authenticate");
         request_body.put("id", "1");
         request_body.put("jsonrpc", "2.0");
         JSONArray params = new JSONArray();
         params.put(user_name);
         params.put(password);
         request_body.put("params", params.toString());
         return request_body;
    }
    @Override
    public String getBodyContentType() {
         return "application/json; charset=utf-8";
    }

};
requestQueueV1.add(stringRequestV1);

我有错误“com.android.volley.TimeoutError”。我该如何解决这个错误?

接下来就是回应

{
    "result": {
        "success": true,
        "items": [
            {
                "apiKey": "4902ad6c957144aba697995f8",
                "userID": "41426322"
            }
        ],
        "total": 1
    },
    "id": "1",
    "jsonrpc": "2.0"
}

获取成功时如何传递此响应 json 对象。

以下是我的邮递员截图:

【问题讨论】:

  • 你是用 localhost 作为服务器吗?
  • 感谢您的回复。我正在使用远程服务器

标签: android post android-volley


【解决方案1】:

在您的 stringRequestV1 下方添加它,然后再将其添加到 Requestqueue。

stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(4000, 2, 2f));

其中 4000 是 TIMEOUT_MS,2 是 DEFAULT_MAX_RETRIES,2f 是 DEFAULT_BACKOFF_MULT

您可以使用下面的默认截击超时设置。

stringRequestV1.setRetryPolicy(new DefaultRetryPolicy(
5000, 
DefaultRetryPolicy.DEFAULT_MAX_RETRIES, 
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

【讨论】:

  • 感谢您的回复。我已经添加了你的评论。在添加请求队列之前。但我收到错误:com.android.volley.AuthFailureError.
  • 这是因为您的 API 在请求数据时需要标头中的一些数据。关注 [stackoverflow.com/questions/31891604/…
  • 没有标题。我添加了邮递员的屏幕截图。请检查并推进我。
  • 试试这个。我不确定这一点,但不是 getParams() 而是尝试 getHeaders()。
  • 如您在屏幕截图中看到的,即请求正文,而不是标头
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 2021-03-11
  • 2019-01-26
  • 2021-10-15
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
相关资源
最近更新 更多