Android使用Volley发起REST GET请求未进入Request方法求助
问题分析与解决方案
你的问题核心在于Volley的JsonObjectRequest是异步执行的,而你的getCall方法是同步返回结果的——在网络请求还没拿到响应的时候,方法就已经返回了初始值null,这就是为什么你始终得不到正确的JSONObject。
具体问题拆解
先看你的代码里的关键问题:
public JSONObject getCall(String url){ final JSONObject temp=null; try{ JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { JSONObject temp1; @Override public void onResponse(JSONObject response) { temp1=response; System.out.println(response); } public JSONObject getTemp1() { return temp1; } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); } }); } catch (Exception e){ System.out.println(e.getMessage()); } return temp; // 这里在请求完成前就返回了,temp永远是null }
temp初始化为null,并且异步请求的回调还没触发时,方法就直接返回了这个值,完全没用到回调里的temp1。temp1是Response.Listener匿名类内部的变量,作用域仅限于这个类,外部方法根本无法在回调执行时拿到它的值。- 你甚至没有把
request添加到Volley的请求队列里!这也是为什么你说“并未进入JSONObjectRequest方法”——因为请求根本没被执行。
正确的实现方式:使用回调接口
因为网络请求是异步的,我们不能用同步方法直接返回结果,而是要通过回调接口在请求完成后通知调用者。
步骤1:定义一个回调接口
public interface VolleyCallback { void onSuccess(JSONObject result); void onError(VolleyError error); }
步骤2:修改getCall方法,接收回调并启动请求
public void getCall(String url, final VolleyCallback callback){ try{ JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { System.out.println(response); callback.onSuccess(response); // 请求成功时传递结果 } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { error.printStackTrace(); callback.onError(error); // 请求失败时传递错误 } }); // 必须把请求添加到Volley队列才会执行! // 假设你已经初始化了RequestQueue实例(比如在Application中) requestQueue.add(request); } catch (Exception e){ System.out.println(e.getMessage()); callback.onError(new VolleyError(e.getMessage())); } }
步骤3:调用方法时通过回调获取结果
getCall("你的请求URL", new VolleyCallback() { @Override public void onSuccess(JSONObject result) { // 在这里处理成功拿到的JSONObject // 比如解析数据、更新UI等操作 } @Override public void onError(VolleyError error) { // 处理请求失败的情况 } });
额外注意点
- 确保你已经正确初始化Volley的
RequestQueue,推荐在Application类中全局初始化:
RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
- Volley的回调会自动在主线程执行,所以你可以直接在
onSuccess里更新UI,不需要手动切换线程。
内容的提问来源于stack exchange,提问作者abhilash mt
相关产品推荐
相关产品推荐

