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

How to get response code from synchronous RequestFuture request

我正在使用 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。我如何区分抛出的错误。

非常感谢您的帮助!

根据您的要求覆盖 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;
    }
};

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

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