我使用谷歌排球在Android平台上。
我有一个问题,即在 onErrorResponse
的错误
参数返回一个空 networkResponse
因为我现在用的是REST的API,我需要确定HTTP状态code这往往是到达401(SC_UNAUTHORIZED)或500(SC_INTERNAL_SERVER_ERROR),我可以通过偶尔检查:
I am using Google Volley on the Android platform.
I am having a problem in which the error
parameter in onErrorResponse
is returning a null networkResponse
For the RESTful API I am using, I need to determine the Http Status Code which is often arriving as 401 (SC_UNAUTHORIZED) or 500 (SC_INTERNAL_SERVER_ERROR), and I can occasionally check via:
final int httpStatusCode = error.networkResponse.statusCode;
if(networkResponse == HttpStatus.SC_UNAUTHORIZED) {
// Http status code 401: Unauthorized.
}
这将引发 NullPointerException异常
,因为 networkResponse
为空。
如何确定在功能HTTP状态code onErrorResponse
?
How can I determine the Http Status Code in the function onErrorResponse
?
或者,我怎么能保证 error.networkResponse
非空的 onErrorResponse
?
Or, how can I ensure error.networkResponse
is non-null in onErrorResponse
?
事实证明,这是不可能保证error.networkResponse非空,而无需修改,因为这将引发异常 NoConnectionError 在BasicNetwork.java Http状态code 401(
HttpStatus.SC_UNAUTHORIZED
)(134)前设置 networkResponse 。
It turns out that it is impossible to guarantee that error.networkResponse is non-null without modifying Google Volley code because of a bug in Volley that throws the Exception NoConnectionError
for Http Status Code 401 (HttpStatus.SC_UNAUTHORIZED
) in BasicNetwork.java (134) prior to setting the value of networkResponse
.
,我们在这种情况下的解决方案是修改Web服务API发送的HTTP错误code 403( HttpStatus.SC_FORBIDDEN )所讨论的特定情况下
Instead of fixing the Volley code, our solution in this case was to modify the Web Service API to send Http Error Code 403 (HttpStatus.SC_FORBIDDEN
) for the particular case in question.
有关此HTTP状态code,值 error.networkResponse
非空的凌空错误处理程序:公共无效onErrorResponse (VolleyError错误)
。而且, error.networkResponse.httpStatus code
正确返回 HttpStatus.SC_FORBIDDEN
。
For this Http Status Code, the value of error.networkResponse
is non-null in the Volley error handler: public void onErrorResponse(VolleyError error)
. And, error.networkResponse.httpStatusCode
correctly returns HttpStatus.SC_FORBIDDEN
.
延长请求 - 其中的Rperryng的建议; T>
类可能提供一个解决方案,并且是一个具有创造性的好主意。非常感谢您的详细例子。我发现我们的情况下,最佳的解决方案是使用变通,因为我们有幸拥有Web服务API的控制权。
Rperryng's suggestion of extending the Request<T>
class may have provided a solution, and is a creative and excellent idea. Thank you very much for the detailed example. I found the optimal solution for our case is to use the work-around because we are fortunate enough to have control of the web services API.
我可能会选择固定凌空code的范围内BasicNetwork.java一个地方,如果我没有访问使得在服务器上的简单变化。
I might opt for fixing the Volley code in one location within BasicNetwork.java if I did not have access to making a simple change at the server.