@Override protected com.android.volley.Response<String> parseNetworkResponse(NetworkResponse response) { this.statusCode = response.statusCode; this.responseHeaders = response.headers; /* Get the response data */ try { String json = ""; if (response.data != null) { json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); } String log = "%1$s\nResponse code: %2$s\nResponse body: %3$s"; VolleyLog.v(log, getUrl(), statusCode, json); if (statusCode >= 200 && statusCode < 300) { /* Return the parsed result in a response wrapper */ return shouldCache() ? success(json, parseIgnoreCacheHeaders(response)) : success(json, parseCacheHeaders(response)); } else { return error(new ServerError(response)); } } catch (UnsupportedEncodingException e) { return error(new ParseError(e)); } }
/** * Show an error dialog based on the exception * * @param exception The exception which occurred * @param context The current context * @param finish Whether or not to finish this activity * @return The dialog which is shown */ public static void showErrorDialog(final Exception exception, final Activity context, final boolean finish) { if (exception instanceof ServerError) { if (((ServerError) exception).networkResponse != null) { if (((ServerError) exception).networkResponse.statusCode == 404) { showNotFoundErrorDialog(context, finish); } else if (((ServerError) exception).networkResponse.statusCode == 500) { showServerErrorDialog(context, finish); } else { showServerErrorDialog(context, finish); } } else { showGeneralErrorDialog(context, finish); } } else if (exception instanceof NoConnectionError){ showNetworkErrorDialog(context, finish); } else { showGeneralErrorDialog(context, finish); } }
public static String checkErrorType(VolleyError error) { String str = ""; if (error instanceof NoConnectionError) { str = ErrorCode.IS_NOT_NETWORK; } else if (error instanceof AuthFailureError) { str = ErrorCode.AUTH_FAILED; } else if (error instanceof TimeoutError) { str = ErrorCode.CONNECTION_TIMEOUT; } else if (error instanceof ParseError) { str = ErrorCode.PARSE_DATA_ERROR; } else if (error instanceof ServerError) { str = ErrorCode.SERVER_ERROR; } else if (error instanceof HttpError) { HttpError httpError = (HttpError) error; str = httpError.getMessage(); if (TextUtils.isEmpty(str)) { str = ErrorCode.REQUEST_ERROR; } } else { str = ErrorCode.REQUEST_ERROR; } return str; }
public Object call() { Object response; try { response = mCallbacks.get(); } catch (Exception e) { ServerError serverError = null; if (e.getCause() instanceof ServerError) { serverError = ((ServerError) e.getCause()); } throw new HttpErrorException(parseError(serverError)); } return parseResponse(response); }
public static String getMessage(VolleyError error){ if (error instanceof TimeoutError) { return TIME_OUT; } else if(error instanceof NoConnectionError) { return NO_CONNECTION; } else if (error instanceof AuthFailureError) { return AUTH_FAILURE; } else if (error instanceof ServerError) { return SERVER; } else if (error instanceof NetworkError) { return NETWORK; } else if (error instanceof ParseError) { return PARSE; } else{ return DEFAULT; } }
@Test public void serverError_enableRetries() throws Exception { for (int i = 500; i <= 599; i++) { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, ""); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack, new ByteArrayPool(4096)); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); request.setShouldRetryServerErrors(true); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should retry all 500 errors verify(mMockRetryPolicy).retry(any(ServerError.class)); reset(mMockRetryPolicy); } }
/** * 判断是否有网络 或者 server无响应等非Client端请求参数异常 * * @param error VolleyError * @return isConnectionError */ public boolean isConnectionError(VolleyError error) { if (error == null) { return false; } if (error instanceof TimeoutError) { return true; } if (error instanceof NoConnectionError) { return true; } if (error instanceof NetworkError) { return true; } if (error instanceof ServerError) { return true; } if (error instanceof RedirectError) { return true; } if (error instanceof AuthFailureError) { return true; } return false; }
@Test public void serverError_enableRetries() throws Exception { for (int i = 500; i <= 599; i++) { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse( new ProtocolVersion("HTTP", 1, 1), i, ""); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack, new ByteArrayPool(4096)); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); request.setShouldRetryServerErrors(true); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should retry all 500 errors verify(mMockRetryPolicy).retry(any(ServerError.class)); reset(mMockRetryPolicy); } }
public static String get(Context paramContext, VolleyError paramVolleyError) { if ((paramVolleyError instanceof DisplayMessageError)) { return ((DisplayMessageError)paramVolleyError).mDisplayErrorHtml; } if ((paramVolleyError instanceof AuthFailureError)) { return paramContext.getString(2131361869); } if ((paramVolleyError instanceof ServerError)) { return paramContext.getString(2131362721); } if ((paramVolleyError instanceof TimeoutError)) { return paramContext.getString(2131362787); } if ((paramVolleyError instanceof NetworkError)) { return paramContext.getString(2131362362); } FinskyLog.d("No specific error message for: %s", new Object[] { paramVolleyError }); return paramContext.getString(2131362362); }
protected final Response<String> parseNetworkResponse(NetworkResponse paramNetworkResponse) { if (paramNetworkResponse.data.length == 0) { if (((Boolean)G.enableSensitiveLogging.get()).booleanValue()) { Object[] arrayOfObject2 = new Object[1]; arrayOfObject2[0] = this.mCvc; FinskyLog.w("Empty escrow handle for cvc %s", arrayOfObject2); } Object[] arrayOfObject1 = new Object[1]; arrayOfObject1[0] = this.mUserId; FinskyLog.wtf("Null response for Escrow string with id %s", arrayOfObject1); return Response.error(new ServerError(paramNetworkResponse)); } return super.parseNetworkResponse(paramNetworkResponse); }
private static int convertErrorCode(Throwable paramThrowable) { if ((paramThrowable instanceof ServerError)) { return -1; } if ((paramThrowable instanceof NetworkError)) { return -2; } if ((paramThrowable instanceof AuthFailureError)) { return -3; } if ((paramThrowable instanceof TimeoutError)) { return -4; } return 0; }
public static OsaException transToOsaException(Throwable a) { if (a == null) { return new OsaException("未知错误"); } if (a instanceof ParseError) { return new OsaException("数据解析错误", a); } if (a instanceof TimeoutError) { return new OsaException("请求超时", a); } if (a instanceof ServerError) { return new OsaException("服务器错误", a); } if (a instanceof AuthFailureError) { return new OsaException("请求认证错误", a); } if (a instanceof NoConnectionError) { return new OsaException("网络未连接,请检查网络状态", a); } if (a instanceof NetworkError) { return new OsaException("网络连接异常", a); } return new OsaException("未知错误"); }
@Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); Log.d("RVA", "error:" + error); int errorCode = 0; if (error instanceof TimeoutError) { errorCode = -7; } else if (error instanceof NoConnectionError) { errorCode = -1; } else if (error instanceof AuthFailureError) { errorCode = -6; } else if (error instanceof ServerError) { errorCode = 0; } else if (error instanceof NetworkError) { errorCode = -1; } else if (error instanceof ParseError) { errorCode = -8; } Toast.makeText(contextHold, ErrorCode.errorCodeMap.get(errorCode), Toast.LENGTH_SHORT).show(); }
private void showError(VolleyError error) { //In your extended request class dismissProgressBar(); if (error.networkResponse != null && error.networkResponse.data != null) { VolleyError volleyError = new VolleyError(new String(error.networkResponse.data)); volleyError.printStackTrace(); } if (error instanceof NetworkError) { showToast(NETWORK_ERROR); } else if (error instanceof ServerError) { showToast(SERVER_ERROR); } else if (error instanceof NoConnectionError) { showToast(NO_INTERNET_CONNECTION); } else if (error instanceof TimeoutError) { showToast(CONNECTION_TIME_OUT); } else { showToast(UNKNOWN_ERROR); } }
private long postCheckIn(String attendeeId, String eventId, boolean revert, String cookie) { RequestQueue queue = GutenbergApplication.from(getContext()).getRequestQueue(); RequestFuture<JSONObject> future = RequestFuture.newFuture(); queue.add(new CheckInRequest(cookie, eventId, attendeeId, revert, future, future)); try { JSONObject object = future.get(); return object.getLong("checkinTime"); } catch (InterruptedException | ExecutionException | JSONException e) { Throwable cause = e.getCause(); if (cause instanceof ServerError) { ServerError error = (ServerError) cause; Log.e(TAG, "Server error: " + new String(error.networkResponse.data)); } Log.e(TAG, "Cannot sync checkin.", e); } return -1; }
public String handlerException(VolleyError error) { if (error instanceof TimeoutError || error instanceof NoConnectionError) { return "连接服务器失败"; } else if (error instanceof AuthFailureError) { return "服务器验证失败"; } else if (error instanceof ServerError) { return "服务器出错了"; } else if (error instanceof NetworkError) { return "网络异常"; } else if (error instanceof ParseError) { return "数据解析异常"; } else { Log.d("error", error.toString()); return "其他错误"; } }
private void post() { BaseRequest request = new BaseRequest(Request.Method.POST, "http://192.168.2.19:5000/test1", new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { Toast.makeText(getActivity(), jsonObject.toString(), Toast.LENGTH_SHORT).show(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof ServerError) { Toast.makeText(getActivity(), new String(((ServerError) error).networkResponse.data, Charset.defaultCharset()), Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show(); } } } ); // request.form("text", "test " + SystemClock.elapsedRealtime()); request.setTag("request"); OkVolley.getInstance().getRequestQueue().add(request); }
private void initErrorListener(){ errorListener=new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Logger.info("onErrorResponse", getErrorStr(error)+" --> "+getUrl()); if (error instanceof TimeoutError) { LogUpdate.getInstance().addLog(LogDataUtils.FUNCTIONID_LOG_TIMEOUT,getUrl(), String.valueOf(-1), "连接超时"); }else if ((error instanceof ServerError) || (error instanceof AuthFailureError)) { LogUpdate.getInstance().addLog(LogDataUtils.FUNCTIONID_LOG_TIMEOUT,getUrl(), String.valueOf(-1), "网络连接异常,请稍后再试"); } onFailure(0,getErrorStr(error)); onEnd(); } }; }
@Override public void onErrorResponse(VolleyError e) { if (e.networkResponse != null) Log.d(ErrorResponseListener.class, "Network Error", "" + e.networkResponse.statusCode + " " + String.valueOf(e.networkResponse.data)); // Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button. // For AuthFailure, you can re login with user credentials. // For ClientError, 400 & 401, Errors happening on client side when sending api request. // In this case you can check how client is forming the api and debug accordingly. // For ServerError 5xx, you can do retry or handle accordingly. if (e instanceof AuthFailureError) { Intent intent = new Intent(Constants.AUTH_FAILURE_BROADCAST_EVENT); context.sendBroadcast(intent); Log.d(ErrorResponseListener.class, "AuthFailureError: ", e.getStackTrace().toString()); } else if (e instanceof NetworkError) { } else if (e instanceof ServerError) { } else if (e instanceof ParseError) { } else if (e instanceof NoConnectionError) { } else if (e instanceof TimeoutError) { } }
@Override public void onErrorResponse(VolleyError error) { setSupportProgressBarIndeterminateVisibility(false); if(error instanceof Article.InvalidArticleError){ Intent intent = new Intent(Intent.ACTION_VIEW); intent.addCategory(Intent.CATEGORY_DEFAULT); intent.setData(Uri.parse("av://ac"+aid)); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(intent); finish(); } catch (Exception e) { //http://www.acfun.tv/lite/v/#ac=1317054 mWeb.loadUrl("http://"+ArticleApi.getDomainRoot(this)+"/lite/v/#ac="+aid); } }else if(error instanceof ServerError){ mWeb.loadUrl("http://"+ArticleApi.getDomainRoot(this)+"/lite/v/#ac="+aid); }else{ showErrorDialog(); } }
/** Reads the contents of HttpEntity into a byte[]. */ private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError { PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); byte[] buffer = null; try { InputStream in = entity.getContent(); if (in == null) { throw new ServerError(); } buffer = mPool.getBuf(1024); int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } return bytes.toByteArray(); } finally { try { // Close the InputStream and release the resources by "consuming the content". entity.consumeContent(); } catch (IOException e) { // This can happen if there was an exception above that left the entity in // an invalid state. VolleyLog.v("Error occured when calling consumingContent"); } mPool.returnBuf(buffer); bytes.close(); } }
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { if (mNumExceptionsToThrow > 0 || mNumExceptionsToThrow == ALWAYS_THROW_EXCEPTIONS) { if (mNumExceptionsToThrow != ALWAYS_THROW_EXCEPTIONS) { mNumExceptionsToThrow--; } throw new ServerError(); } requestHandled = request; return new NetworkResponse(mDataToReturn); }
private void fetchData() { wheel.setVisibility(View.VISIBLE); RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue(); StringRequest req = new StringRequest(Request.Method.GET, API.BASE_IMAGE_URL + showID + "/actors.xml", new Response.Listener<String>() { @Override public void onResponse(String response) { new loadData().execute(response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof TimeoutError || error instanceof NoConnectionError) { tvError.setText(R.string.timeout_error); } else if (error instanceof ServerError) { tvError.setText(R.string.server_error); } else if (error instanceof NetworkError) { tvError.setText(R.string.network_error); } else { tvError.setText(R.string.connection_error); } tapToRetry.setVisibility(View.VISIBLE); wheel.setVisibility(View.GONE); } }); requestQueue.add(req); }
private void fetchData() { wheel.setVisibility(View.VISIBLE); RequestQueue requestQueue = VolleySingleton.getInstance().getRequestQueue(); StringRequest req = new StringRequest(Request.Method.GET, API.BASE_IMAGE_URL + showID + "/banners.xml", new Response.Listener<String>() { @Override public void onResponse(String response) { final String imageURL = API.TVDB_LINK + "banners/"; imageArray.clear(); try { JSONObject jsonObjectResponse = XML.toJSONObject(response); JSONArray bannerList = jsonObjectResponse.getJSONObject("Banners").getJSONArray("Banner"); for (int i = 0; i < bannerList.length(); i++) { JSONObject imageObject = bannerList.getJSONObject(i); if (imageObject.optString("BannerType").equals(imageName[imageType])) { ShowImageItem imageItem = new ShowImageItem(); imageItem.setImagePath(imageURL + imageObject.optString("BannerPath")); String thumbnailPath = imageObject.optString("ThumbnailPath", ""); if (!thumbnailPath.equals("")) { imageItem.setThumbnailPath(imageURL + thumbnailPath); } else { imageItem.setThumbnailPath(""); } imageArray.add(imageItem); } } wheel.setVisibility(View.GONE); adapter.notifyDataSetChanged(); } catch (JSONException e) { wheel.setVisibility(View.GONE); Log.e("ShowImageActivity", String.valueOf(e)); tvError.setText(R.string.no_images_available); tapToRetry.setVisibility(View.VISIBLE); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (error instanceof TimeoutError) { tvError.setText(R.string.timeout_error); } else if (error instanceof ServerError) { tvError.setText(R.string.server_error); } else { tvError.setText(R.string.connection_error); } tapToRetry.setVisibility(View.VISIBLE); wheel.setVisibility(View.GONE); } }); requestQueue.add(req); }
private void handleNetworkError(VolleyError error) { if (error instanceof TimeoutError || error instanceof NoConnectionError) { getView().showTimeOutError(); } else if (error instanceof ServerError) { getView().show500ServerError(); } else if (error instanceof NetworkError) { getView().showNetworkError(); } }
private void handleErrors(VolleyError error) { if (error instanceof TimeoutError || error instanceof NoConnectionError) { getView().showTimeOutError(); } else if (error instanceof ServerError) { getView().show500ServerError(); } else if (error instanceof NetworkError) { getView().showNetworkError(); } }
/** * Reads the contents of HttpEntity into a byte[]. */ private byte[] entityToBytes(HttpEntity entity) throws IOException, ServerError { PoolingByteArrayOutputStream bytes = new PoolingByteArrayOutputStream(mPool, (int) entity.getContentLength()); byte[] buffer = null; try { InputStream in = entity.getContent(); if (in == null) { throw new ServerError(); } buffer = mPool.getBuf(1024); int count; while ((count = in.read(buffer)) != -1) { bytes.write(buffer, 0, count); } return bytes.toByteArray(); } finally { try { // Close the InputStream and release the resources by "consuming the content". entity.consumeContent(); } catch (IOException e) { // This can happen if there was an exception above that left the entity in // an invalid state. VolleyLog.v("Error occured when calling consumingContent"); } mPool.returnBuf(buffer); bytes.close(); } }