我想处理并在onErrorResponse
下面是我的代码。
String url = MainActivity.strHostUrl+"api/delete_picture";
jobjDeleteImage = new JsonObjectRequest(Request.Method.POST, url, jobj, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.e("Image response", response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volly Error", error.toString());
NetworkResponse networkResponse = error.networkResponse;
if (networkResponse != null) {
Log.e("Status code", String.valueOf(networkResponse.statusCode));
}
}
});
我想在这里处理com.android.volley.TimeoutError
以及其他一些错误代码,例如404,503等和Toast
消息。
答案 0 :(得分:110)
networkResponse为null,因为在TimeoutError中没有从服务器收到数据 - 因此超时。相反,当发生其中一个事件时,您需要显示通用客户端字符串。您可以使用instanceof检查VolleyError的类型,以区分错误类型,因为您没有可以使用的网络响应 - 例如:
@Override
public void onErrorResponse(VolleyError error) {
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(context,
context.getString(R.string.error_network_timeout),
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
}
答案 1 :(得分:2)
你也有TimeoutError和NoConnectionError。超级实用。
答案 2 :(得分:1)
这就是我在项目中使用的东西。
@Override
public void onErrorResponse(VolleyError error) {
if(error instanceof NoConnectionError){
ConnectivityManager cm = (ConnectivityManager)mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = null;
if (cm != null) {
activeNetwork = cm.getActiveNetworkInfo();
}
if(activeNetwork != null && activeNetwork.isConnectedOrConnecting()){
Toast.makeText(getActivity(), "Server is not connected to internet.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "Your device is not connected to internet.",
Toast.LENGTH_SHORT).show();
}
} else if (error instanceof NetworkError || error.getCause() instanceof ConnectException
|| (error.getCause().getMessage() != null
&& error.getCause().getMessage().contains("connection"))){
Toast.makeText(getActivity(), "Your device is not connected to internet.",
Toast.LENGTH_SHORT).show();
} else if (error.getCause() instanceof MalformedURLException){
Toast.makeText(getActivity(), "Bad Request.", Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError || error.getCause() instanceof IllegalStateException
|| error.getCause() instanceof JSONException
|| error.getCause() instanceof XmlPullParserException){
Toast.makeText(getActivity(), "Parse Error (because of invalid json or xml).",
Toast.LENGTH_SHORT).show();
} else if (error.getCause() instanceof OutOfMemoryError){
Toast.makeText(getActivity(), "Out Of Memory Error.", Toast.LENGTH_SHORT).show();
}else if (error instanceof AuthFailureError){
Toast.makeText(getActivity(), "server couldn't find the authenticated request.",
Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError || error.getCause() instanceof ServerError) {
Toast.makeText(getActivity(), "Server is not responding.", Toast.LENGTH_SHORT).show();
}else if (error instanceof TimeoutError || error.getCause() instanceof SocketTimeoutException
|| error.getCause() instanceof ConnectTimeoutException
|| error.getCause() instanceof SocketException
|| (error.getCause().getMessage() != null
&& error.getCause().getMessage().contains("Connection timed out"))) {
Toast.makeText(getActivity(), "Connection timeout error",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(), "An unknown error occurred.",
Toast.LENGTH_SHORT).show();
}
}
答案 3 :(得分:0)
您可以使用自定义排球等级来处理凌空快速响应 像这样:排球班:
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.LruCache;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import static android.content.ContentValues.TAG;
public class VolleyClass {
private static VolleyClass mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private Context mCtx;
private int time = 0;
public VolleyClass(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue,
new ImageLoader.ImageCache() {
private final LruCache<String, Bitmap>
cache = new LruCache<>(20);
@Override
public Bitmap getBitmap(String url) {
return cache.get(url);
}
@Override
public void putBitmap(String url, Bitmap bitmap) {
cache.put(url, bitmap);
}
});
}
public static synchronized VolleyClass getInstance(Context context) {
if (mInstance == null) {
mInstance = new VolleyClass(context);
}
return mInstance;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
req.setRetryPolicy(new DefaultRetryPolicy(
time,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
getRequestQueue().add(req);
}
private RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
//mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext());
mRequestQueue = Volley.newRequestQueue(mCtx.getApplicationContext(), new OkHttpStack(new com.squareup.okhttp.OkHttpClient()));
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
req.setRetryPolicy(new DefaultRetryPolicy(
time,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
getRequestQueue().add(req);
}
/*public ImageLoader getImageLoader() {
return mImageLoader;
}*/
}
&#13;
Sinc gradle with 编译&#39; com.android.volley:volley:1.0.0&#39; 编译&#39; com.squareup.okhttp3:okhttp:3.8.1&#39;
初步排球: VolleyClass volleyClass; volleyClass = new VolleyClass(this); //在onCreate下 然后调用该方法进行操作 1.row data:
private void serverCall() {
final ProgressDialog mDialog = new ProgressDialog(SettingActivity.this);
mDialog.setMessage("Please wait...");
mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mDialog.setIndeterminate(true);
mDialog.setCancelable(false);
mDialog.show();
JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, "your url", null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
mDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
mDialog.dismiss();
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("User-agent", System.getProperty("http.agent"));
return headers;
}
@Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
volleyClass.addToRequestQueue(jsObjRequest);
}
private void networkCallPostData(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, "url",
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("response", response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
System.out.println("VolleyError " + error.getMessage());
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("id",app.getAppSettings().__uId);
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
//headers.put("Content-Type", "application/json; charset=utf-8");
headers.put("Content-Type", "multipart/form-data");
headers.put("User-agent", System.getProperty("http.agent"));
return headers;
}
@Override
public Priority getPriority() {
return Priority.IMMEDIATE;
}
};
volleyClass.addToRequestQueue(stringRequest);
}
答案 4 :(得分:0)
在Android Volley example with Error Handling
了解有关Volley错误处理的更多信息每个Volley请求都有两个回调 - 一个用于成功,一个用于失败。基于onErrorResponse回调中VolleyError参数的类型,开发人员可以向用户显示合理的消息,如下所示
@Override
public void onErrorResponse (VolleyError error){
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
//This indicates that the reuest has either time out or there is no connection
} else if (error instanceof AuthFailureError) {
// Error indicating that there was an Authentication Failure while performing the request
} else if (error instanceof ServerError) {
//Indicates that the server responded with a error response
} else if (error instanceof NetworkError) {
//Indicates that there was network error while performing the request
} else if (error instanceof ParseError) {
// Indicates that the server response could not be parsed
}
}
答案 5 :(得分:-3)
/**
* Http 访问失败
*
*
*/
@Override
public void error(VolleyError error){
NetworkResponse response = error.networkResponse;
if(response != null && response.data != null){
Toast.makeText(context,"errorMessage:"+response.statusCode, Toast.LENGTH_SHORT).show();
}else{
String errorMessage=error.getClass().getSimpleName();
if(!TextUtils.isEmpty(errorMessage)){
Toast.makeText(context,"errorMessage:"+errorMessage, Toast.LENGTH_SHORT).show();
}
}
}//public void error(VolleyError error) is over! zlb