Android Volley发布请求,体内带有json对象,并在String中获取响应

Sho*_*ool 1 post android android-volley

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

Body:
{
     "username": "Shozib@gmail.com",
     "password": "Shozib123"
  }
Run Code Online (Sandbox Code Playgroud)

回应:“ k5ix28k9ikhtcqys4swatnfvohrcg0lp

Ram*_*mbu 5

尝试这个

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();
}
Run Code Online (Sandbox Code Playgroud)

  • 我明白了,在上面的代码中,我们覆盖了“responseString = String.valueOf(response.statusCode);”,如果我在评论 parseNetworkRespose,它会返回实际的字符串 (2认同)