如何从同步请求未来请求中获取响应代码



我正在使用 strava API 用于应用程序。我正在发出同步请求,如下面的代码所示。

try {
RequestQueue queue = Volley.newRequestQueue(context);
RequestFuture<String> future = RequestFuture.newFuture();
StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future);
queue.add(request);
dataResponse = dealWithResponse(future.get()); 
} catch (ExecutionException e) {
System.err.println(e.getLocalizedMessage());
System.err.println(e.getMessage());
System.err.println(e.toString());
} catch (java.lang.Exception e) {
e.printStackTrace();
}

我想知道如何在发生错误时获取响应代码? 例如,我请求的某些游乐设施已被删除/是私有的,并且我收到了 404 错误代码。其他时候我已经用完了 API 请求并得到代码 403。如何区分抛出的错误。

非常感谢您的帮助!

在处理ExecutionException的 catch 子句中,您可以添加以下内容:

if (e.getCause() instanceof ClientError) {
ClientError error = (ClientError)e.getCause();
switch (error.networkResponse.statusCode) {
//Handle error code
}
}

根据您的请求覆盖parseNetworkError

StringRequest request = new StringRequest(Request.Method.GET, urlRequest, future, future) {
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if (volleyError != null && volloeyError.networkResponse != null) {
int statusCode = volleyError.networkResponse.statusCode;
switch (statusCode) {
case 403:
// Forbidden
break;
case 404:
// Page not found
break;
}
}
return volleyError;
}
};

最新更新