Android中使用json对象并在字符串

时间:2018-01-24 13:46:38

标签: android post android-volley

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

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

响应: “k5ix28k9ikhtcqys4swatnfvohrcg0lp

1 个答案:

答案 0 :(得分:4)

试一下

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();
}
相关问题