简体   繁体   中英

Get the HTTP body response of a POST with volley-android

I am trying to get in my app some data and show to the user by using an HTTP POST request with Volley. My issue is that I don't know how to get the server Body response to the request. In the code below the response is always "200" which turns to be the HTTP status code.

How can I extract the body response and manage as a string?

 RequestQueue requestQueue = Volley.newRequestQueue(this);
    final String requestBody = Utility.toCorrectCase(req);
    //Decommentare solo per il debug
    //Toast.makeText(getBaseContext(),requestBody, Toast.LENGTH_SHORT).show();
    StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.i("VOLLEY", response);
            Bitmap myBitmap = QRCode.from(response).bitmap();
            qrcode.setImageBitmap(myBitmap);
            ViewGroup.LayoutParams params = qrcode.getLayoutParams();
            params.width =  qrDisplayedSize;
            params.height = qrDisplayedSize;
            qrcode.setLayoutParams(params);
            loadingText.setText(getString(R.string.prod_id_desc).concat(response));
            qrcode.setVisibility(View.VISIBLE);
            backButton.setVisibility(View.VISIBLE);
            progressBar.setVisibility(View.INVISIBLE);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.d("VOLLEY", error.toString());
            new SweetAlertDialog(getApplicationContext(), SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("Errore comunicazione server")
                    .setContentText("Qualcosa non ha funzionato!\nDescrizione errore:".concat(error.toString()))
                    .show();
            finish();
        }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=utf-8";
        }

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

        @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {
            String responseString;
            responseString = String.valueOf(response.statusCode);

            return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
        }
    };
    requestQueue.add(stringRequest);

After days of searches, I've found out that I have not overridden correctly the networkResponse. So for everyone with my same trouble, the answer of my question is: parseNetworkResponse must be overridden to get response body in an easisest way.

            @Override
        protected Response<String> parseNetworkResponse(NetworkResponse response) {

            if(response.statusCode==400){
                new SweetAlertDialog(getApplicationContext(), SweetAlertDialog.ERROR_TYPE)
                        .setTitleText("Errore comunicazione server")
                        .setContentText("Qualcosa non ha funzionato!\nCodice errore:"+response.statusCode)
                        .show();
                finish();
            }
            return super.parseNetworkResponse(response);
        }

change this it works for me

@Override
    protected Response < String > parseNetworkResponse(NetworkResponse response) {

     String parsed;
     try {
      parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
     } catch (UnsupportedEncodingException e) {
      parsed = new String(response.data);
     }
     return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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