我实现了一个带有 volley 库的 Android 应用程序来连接我的数据库。与“get”和“post”请求的连接有效,但服务器响应不起作用。
发生这种情况是因为错误响应会自动捕获错误(例如,我的服务器响应代码为 201 表示登录成功,但齐射将其理解为错误)。
我重写 Request 类中的 parseNetworkError:
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
String parsed;
NetworkResponse networkResponse = volleyError.networkResponse;
if(networkResponse != null && networkResponse.data != null) {
try {
parsed = new String(networkResponse.data, HttpHeaderParser.parseCharset(networkResponse.headers));
} catch (UnsupportedEncodingException var4) {
parsed = new String(networkResponse.data);
}
NetworkResponse response = new NetworkResponse(networkResponse.data);
Response<String> parsedResponse;
switch(response.statusCode){
case 204:
...
case 401:
...
default:
return volleyError;
}
}
return super.parseNetworkError(volleyError);
}
问题是 VolleyError。此类扩展了 Exception 并且不包含信息(代码错误)。
我该如何解决这个问题?
你可以这样处理
@Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user credentials.
// 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( error instanceof NetworkError) {
//handle your network error here.
} else if( error instanceof ServerError) {
//handle if server error occurs with 5** status code
} else if( error instanceof AuthFailureError) {
//handle if authFailure occurs.This is generally because of invalid credentials
} else if( error instanceof ParseError) {
//handle if the volley is unable to parse the response data.
} else if( error instanceof NoConnectionError) {
//handle if no connection is occurred
} else if( error instanceof TimeoutError) {
//handle if socket time out is occurred.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)