无法在凌空访问StringRequest之外的响应

问题描述 投票:0回答:1

我用过this简单的获取请求代码

final StringBuilder result = new StringBuilder();
        RequestQueue queue = Volley.newRequestQueue(removeThisIfItDidntWork);
        String url ="https://jsonplaceholder.typicode.com/posts/1";

// Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        result.append(response);
                        System.out.println(result.toString()); //this get the actual result
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });

// Add the request to the RequestQueue.
        queue.add(stringRequest);
        System.out.println(result.toString()); //this result an empty string

当我在响应中打印它时,它会输出预期的结果,但是当我在外面使用它时,它会打印一个空字符串

java android android-volley
1个回答
0
投票

queue.add将请求添加到队列中,以便稍后执行。 result.toString被调用之后,它当然是空的(刚在上面被创建为空,请求尚未执行)。

稍后,从队列中提取请求,执行并接收响应。然后调用onResponse,将response添加到result并打印出来。

欢迎使用多线程的世界:)

© www.soinside.com 2019 - 2024. All rights reserved.