如何访问Volley中的错误响应内容?

时间:2014-10-02 18:56:17

标签: android android-volley

使用以下任何一个示例: http://developer.android.com/training/volley/request.html

我理解如何处理成功请求的响应,以及如何检测错误并做出反应。

但是,错误可能是(在其他情况下)来自服务器的40x或50x响应,在这种情况下,响应仍然可以包含数据(标题和正文)。

但是错误监听器只传递了一个VolleyError对象(如果我没有弄错的话,它是Exception的子类)而不是一个Response对象。

如何访问错误响应的内容?

4 个答案:

答案 0 :(得分:35)

VolleyError对象有一个networkResponse引用,它本身有一个'data'成员,它是响应主体的字节数组。如果要在响应中出现错误代码时查看数据,可以使用以下内容:

@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...
}

答案 1 :(得分:5)

在StringRequest中,例如:

@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);
}

答案 2 :(得分: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";

  

答案 3 :(得分:-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();
    }
}

}

//适配器 public class SixthApiAdapter extends RecyclerView.Adapter {

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

公共类数据项{

@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";