How to access the contents of an error response in Volley?
Asked Answered
P

4

31

Using any of these examples: http://developer.android.com/training/volley/request.html

I understand how to process the response of a succesful request, and how to detect and react to an error.

However, an error may be (among other situations) a 40x or 50x response from the server, in which case the response can still contain data (headers and body).

But the error listener is only passed a VolleyError object (which is a subclass of Exception if I'm not mistaken) and not a Response object.

How do I access the content of an error response?

Patagium answered 2/10, 2014 at 18:56 Comment(0)
C
6

In StringRequest for example:

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    Map<String, String> responseHeaders = response.headers;
    if (response.statusCode == 401) {
        // Here we are, we got a 401 response and we want to do something with some header field; in this example we return the "Content-Length" field of the header as a successfully response to the Response.Listener<String>
        Response<String> result = Response.success(responseHeaders.get("Content-Length"), HttpHeaderParser.parseCacheHeaders(response));
        return result;
    } // else any other code that carries a message
    return super.parseNetworkResponse(response);
}
Cremator answered 31/10, 2014 at 10:58 Comment(1)
There is a '(' missing in if statement, thank you for your answer :)Semantic
A
77

The VolleyError object has a networkResponse reference, which itself has a 'data' member, which is a byte array of the response body. If you want to view the data in the case of an error code in response, you can use something like this:

@Override
public void onErrorResponse(VolleyError error) {
    String body;
    //get status code here
    String statusCode = String.valueOf(error.networkResponse.statusCode);
    //get response body and parse with appropriate encoding
    if(error.networkResponse.data!=null) {
        try {
            body = new String(error.networkResponse.data,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    //do stuff with the body...
}
Almshouse answered 16/4, 2015 at 5:51 Comment(1)
I think you want to do stuff with the body inside the ifWoodchuck
C
6

In StringRequest for example:

@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
    Map<String, String> responseHeaders = response.headers;
    if (response.statusCode == 401) {
        // Here we are, we got a 401 response and we want to do something with some header field; in this example we return the "Content-Length" field of the header as a successfully response to the Response.Listener<String>
        Response<String> result = Response.success(responseHeaders.get("Content-Length"), HttpHeaderParser.parseCacheHeaders(response));
        return result;
    } // else any other code that carries a message
    return super.parseNetworkResponse(response);
}
Cremator answered 31/10, 2014 at 10:58 Comment(1)
There is a '(' missing in if statement, thank you for your answer :)Semantic
L
0
//Activity
public class FifthActivity extends AppCompatActivity {

RequestQueue requestQueue;
StringRequest stringRequest;

AppCompatButton btn_request;
TextView data;
EditText ed_name, ed_salary, ed_age;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fifth);

    ed_name = findViewById(R.id.ed_name);
    ed_salary = findViewById(R.id.ed_salary);
    ed_age = findViewById(R.id.ed_age);

    data = findViewById(R.id.data);

    btn_request = findViewById(R.id.btn_request);

    btn_request.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
//                sendReqAndgetRes();
            sendReqAndgetRes1();
        }
    });
    }

private void sendReqAndgetRes1() {
    JSONObject obj = new JSONObject();
    try {
        obj.put("name", ed_name.getText().toString());
        obj.put("salary", ed_salary.getText().toString());
        obj.put("age", ed_age.getText().toString());
    } catch (JSONException jsonException) {
        jsonException.printStackTrace();
    }

    requestQueue = Volley.newRequestQueue(FifthActivity.this);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, 
 Config.API_URL_Fifth, obj, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            Log.e("Res48", String.valueOf(response));

            try {
                JSONObject jsonObject = new JSONObject(response.toString());
                JSONObject jsonObject1 = jsonObject.getJSONObject("data");

                String a = jsonObject1.getString("name");
                String b = jsonObject1.getString("salary");
                String c = jsonObject1.getString("age");
                int d = Integer.valueOf(jsonObject1.getString("id"));

                data.setText("Name : " + a + "\nSalary : " + b + "\nAge : " + c + 
  "\nId : " + d);
//                    Toast.makeText(FifthActivity.this, "Id : " + d, 
 Toast.LENGTH_SHORT).show();
            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    });
    requestQueue.add(jsonObjectRequest);
   }

private void sendReqAndgetRes() {
    requestQueue = Volley.newRequestQueue(FifthActivity.this);
    stringRequest = new StringRequest(Request.Method.POST, Config.API_URL_Fifth, new 
 Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("Res48", response);
            try {
                JSONObject jsonObject = new JSONObject(response);
                JSONObject jsonObject1 = jsonObject.getJSONObject("data");

                int d = Integer.valueOf(jsonObject1.getString("id"));

                Toast.makeText(FifthActivity.this, "Id : " + d, 
 Toast.LENGTH_SHORT).show();
            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String, String> param = new HashMap<String, String>();
            param.put("name", "test");
            param.put("salary", "123");
            param.put("age", "23");
            return param;
        }
    };

     requestQueue.add(stringRequest);
  }
  }

  //URL
        public static String API_URL_Fifth = "http://dummy.restapiexample.com/api/v1/create";

  
Luellaluelle answered 13/3, 2021 at 11:55 Comment(0)
L
-1
//Activity
 public class SixthActivity extends AppCompatActivity implements SixthApiAdapter.OnItemClickListner {

RequestQueue requestQueue;
StringRequest stringRequest;

ArrayList<DataItem> list = new ArrayList<>();
AppCompatButton btn_request;
RecyclerView recyclerView;
SixthApiAdapter sixthApiAdapter;

DataItem dataItem;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sixth);

    btn_request = findViewById(R.id.btn_request);
    recyclerView = findViewById(R.id.recyclerView);

    sendReqAndgetRes();
}

private void sendReqAndgetRes() {

    requestQueue = Volley.newRequestQueue(SixthActivity.this);

    stringRequest = new StringRequest(Request.Method.POST, Config.API_URL_Third, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                list.clear();
                JSONObject jsonObject = new JSONObject(response);
                JSONArray jsonArray = jsonObject.getJSONArray("data");

                Gson gson = new Gson();
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    dataItem = gson.fromJson(jsonObject1.toString(), DataItem.class);
                    list.add(dataItem);
                }

                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(SixthActivity.this);
                RecyclerView.LayoutManager layoutManager = linearLayoutManager;
                recyclerView.setLayoutManager(layoutManager);
                sixthApiAdapter = new SixthApiAdapter(SixthActivity.this, list, SixthActivity.this);
                recyclerView.setAdapter(sixthApiAdapter);

            } catch (JSONException jsonException) {
                jsonException.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    }) {
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            Map<String, String> params = new HashMap<String, String>();
            params.put("packagename", "com.aytel.aytelallremote");
            return params;
        }
    };

    requestQueue.add(stringRequest);
}

@Override
public void onItemClick(int position) {
    Toast.makeText(this, "Position : " + position, Toast.LENGTH_SHORT).show();

    Toast.makeText(this, "Data: " + list.get(position).getAppName(), Toast.LENGTH_SHORT).show();

    if (position == 0) {
        Toast.makeText(this, "Data : " + list.get(0).getAppName(), Toast.LENGTH_SHORT).show();
    }
    if (position == 1) {
        Toast.makeText(this, "Data : " + list.get(1).getAppName(), Toast.LENGTH_SHORT).show();
    }
}

}

//Adapter public class SixthApiAdapter extends RecyclerView.Adapter<SixthApiAdapter.ViewHolder> {

Context context;
ArrayList<DataItem> list;
DataItem dataItem;

OnItemClickListner listner;

public SixthApiAdapter(Context context, ArrayList<DataItem> list, OnItemClickListner onItemClickListner) {
    this.context = context;
    this.list = list;
    listner = onItemClickListner;
}


@NonNull
@Override
public SixthApiAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater layoutInflater = LayoutInflater.from(context);
    View view = layoutInflater.inflate(R.layout.thirdjsonitem, parent, false);
    ViewHolder viewHolder = new ViewHolder(view,listner);
    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull SixthApiAdapter.ViewHolder holder, int position) {
    dataItem = list.get(position);

    holder.appname.setText(dataItem.getAppName());
    holder.packagename.setText(dataItem.getPackageName());
    Glide.with(context).load(dataItem.getAppIcon()).into(holder.icon);
}

@Override
public int getItemCount() {
    return list.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    ImageView icon;
    TextView appname, packagename;
    OnItemClickListner onItemClickListner;

    public ViewHolder(@NonNull View itemView, OnItemClickListner onItemClickListner) {
        super(itemView);

        icon = itemView.findViewById(R.id.icon);
        appname = itemView.findViewById(R.id.appname);
        packagename = itemView.findViewById(R.id.packagename);

        this.onItemClickListner = onItemClickListner;
        icon.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        onItemClickListner.onItemClick(getAdapterPosition());
    }
}

public interface OnItemClickListner {
    void onItemClick(int position);
}

}

// Json Data

public class DataItem{

@SerializedName("app_name")
private String appName;

@SerializedName("app_icon")
private String appIcon;

@SerializedName("admob_banner")
private String admobBanner;

@SerializedName("privacypolicy")
private Object privacypolicy;

@SerializedName("admob_appid")
private Object admobAppid;

@SerializedName("admob_inter")
private String admobInter;

@SerializedName("fb_banner")
private Object fbBanner;

@SerializedName("fb_native")
private Object fbNative;

@SerializedName("admob_native")
private Object admobNative;

@SerializedName("package_name")
private String packageName;

@SerializedName("fb_inter")
private Object fbInter;

@SerializedName("moreapps")
private Object moreapps;

public void setAppName(String appName){
    this.appName = appName;
}

public String getAppName(){
    return appName;
}

public void setAppIcon(String appIcon){
    this.appIcon = appIcon;
}

public String getAppIcon(){
    return appIcon;
}

public void setAdmobBanner(String admobBanner){
    this.admobBanner = admobBanner;
}

public String getAdmobBanner(){
    return admobBanner;
}

public void setPrivacypolicy(Object privacypolicy){
    this.privacypolicy = privacypolicy;
}

public Object getPrivacypolicy(){
    return privacypolicy;
}

public void setAdmobAppid(Object admobAppid){
    this.admobAppid = admobAppid;
}

public Object getAdmobAppid(){
    return admobAppid;
}

public void setAdmobInter(String admobInter){
    this.admobInter = admobInter;
}

public String getAdmobInter(){
    return admobInter;
}

public void setFbBanner(Object fbBanner){
    this.fbBanner = fbBanner;
}

public Object getFbBanner(){
    return fbBanner;
}

public void setFbNative(Object fbNative){
    this.fbNative = fbNative;
}

public Object getFbNative(){
    return fbNative;
}

public void setAdmobNative(Object admobNative){
    this.admobNative = admobNative;
}

public Object getAdmobNative(){
    return admobNative;
}

public void setPackageName(String packageName){
    this.packageName = packageName;
}

public String getPackageName(){
    return packageName;
}

public void setFbInter(Object fbInter){
    this.fbInter = fbInter;
}

public Object getFbInter(){
    return fbInter;
}

public void setMoreapps(Object moreapps){
    this.moreapps = moreapps;
}

public Object getMoreapps(){
    return moreapps;
}

@Override
public String toString(){
    return 
        "DataItem{" + 
        "app_name = '" + appName + '\'' + 
        ",app_icon = '" + appIcon + '\'' + 
        ",admob_banner = '" + admobBanner + '\'' + 
        ",privacypolicy = '" + privacypolicy + '\'' + 
        ",admob_appid = '" + admobAppid + '\'' + 
        ",admob_inter = '" + admobInter + '\'' + 
        ",fb_banner = '" + fbBanner + '\'' + 
        ",fb_native = '" + fbNative + '\'' + 
        ",admob_native = '" + admobNative + '\'' + 
        ",package_name = '" + packageName + '\'' + 
        ",fb_inter = '" + fbInter + '\'' + 
        ",moreapps = '" + moreapps + '\'' + 
        "}";
    }

}

// URL

public static String API_URL_Third = "https://localads.fuegomasters.com/localadservice/getalladsnew.php";

Luellaluelle answered 13/3, 2021 at 12:38 Comment(1)
That code may work fine and contain the answer, but alongside with that it is a copy-pasted bunch of classes, too excessive and no explanation is provided with that. Would be great if you've made that code somehow more useful and easy to comprehend for a reader.Benedictine

© 2022 - 2024 — McMap. All rights reserved.