简体   繁体   English

如何获得Volley POST响应正文?

[英]How to get Volley POST response body?

I am using simmilar fucntion for creating GET and POST api requests, but the GET function set textview to response body and I dont know how to read the status code and the POST function set textview to the response code and I dont know how to read response body. 我正在使用类似的功能来创建GET和POST api请求,但是GET函数将textview设置为响应正文,我不知道如何读取状态代码,而POST函数将textview设置为响应代码,也不知道如何读取响应身体。 Can you help me, please? 你能帮我吗?

I also tried to log in parseNetworkResponse() response.data.toString() but thats is not the data that api returns. 我也尝试登录parseNetworkResponse()response.data.toString(),但这不是api返回的数据。 Maybe I need to encode it somehow? 也许我需要以某种方式对其进行编码?

public void createGet(Context context, String url) {
      final TextView apiResultTextview = (TextView) ((Activity) 
  context).findViewById(R.id.api_result_textview);
      // Instantiate the RequestQueue.
         RequestQueue queue = Volley.newRequestQueue(context);

    // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    // Display the first 500 characters of the response string.
                    apiResultTextview.setText("Response is: " + response.substring(0, 50));
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            apiResultTextview.setText(error.toString());
        }
    });

    // Add the request to the RequestQueue.
    queue.add(stringRequest);
}

public void createPost(Context context, String url, JSONObject body) {
    final TextView apiResultTextview = (TextView) ((Activity) context).findViewById(R.id.api_result_textview);
    RequestQueue requestQueue = Volley.newRequestQueue(context);
    final String mRequestBody = body.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);
                apiResultTextview.setText("Response is: " + responseString);
            }
            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };
    requestQueue.add(stringRequest);
}

add this code in you onResponse() Method 在您的onResponse()方法中添加此代码

 JSONObject jsonObj = new JSONObject(response);
 String response_value = jsonObj.getString("response");

I solved it by changing method for call to code below. 我通过更改下面的代码调用方法解决了这一问题。 Problem was probably in JsonObjectRequest vs StringRequest. 问题可能出在JsonObjectRequest与StringRequest中。 That's why I was getting only response code string. 这就是为什么我只得到响应代码字符串的原因。

public void createCall(int type, String url, JSONObject data, final int callback) {
    JsonObjectRequest jsonRequest = new JsonObjectRequest(type, url,data,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("Response", response.toString());
                    try {
                        callback(response, callback);
                    } catch (Exception e){
                        Log.d("API callback error", e.getMessage());
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("Error response", error.toString());
                }
            }
    );
    queue.add(jsonRequest);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM