【问题标题】:Android volley post request with json object in body and getting response in String带有json对象的Android volley post请求并在String中获得响应
【发布时间】:2018-12-12 01:58:47
【问题描述】:

我如何在正文中发送json 对象并以字符串形式获得响应?

Body:
{
     "username": "Shozib@gmail.com",
     "password": "Shozib123"
  }

回应: "k5ix28k9ikhtcqys4swatnfvohrcg0lp"

【问题讨论】:

  • 嗨,Shozib,请提供更多详细信息,也许还有一个小代码示例。你试过什么?您能否提供有关预期行为的更多信息?

标签: android post android-volley


【解决方案1】:

试试这个

try {
    RequestQueue requestQueue = Volley.newRequestQueue(this);
    JSONObject jsonBody = new JSONObject();
    jsonBody.put("username", "Shozib@gmail.com");
    jsonBody.put("password", "Shozib123");
    final String mRequestBody = jsonBody.toString();

    StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("LOG_RESPONSE", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("LOG_RESPONSE", error.toString());
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/json; charset=utf-8";
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            try {
                return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
            } catch (UnsupportedEncodingException uee) {
                VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
                return null;
            }
        }

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString = "";
            if (response != null) {
                responseString = String.valueOf(response.statusCode);
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };

    requestQueue.add(stringRequest);
} catch (JSONException e) {
    e.printStackTrace();
}

【讨论】:

  • 谢谢!但它返回的是请求代码,而不是它应该返回的实际字符串
  • 在成功响应中没有它会给出字符串...检查它是打印成功还是错误
  • StringRequeat 会在成功时返回字符串
  • 我明白了,在上面的代码中,我们重写了“responseString = String.valueOf(response.statusCode);”,如果我在评论 parseNetworkRespose 它返回的是实际字符串
  • 点击勾选同意我的回答.. 很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 2016-09-24
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 2020-12-13
  • 1970-01-01
  • 1970-01-01
  • 2021-05-24
相关资源
最近更新 更多