首页 > 解决方案 > 如何从同步 RequestFuture 请求中获取响应代码

问题描述

我正在为应用程序使用 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 的代码。我如何区分抛出的错误。

非常感谢您的帮助!

标签: javaandroiderror-codeurlrequestrequest-queueing

解决方案


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

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

推荐阅读