我用过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
当我在响应中打印它时,它会输出预期的结果,但是当我在外面使用它时,它会打印一个空字符串
queue.add
将请求添加到队列中,以便稍后执行。 result.toString
被调用之后,它当然是空的(刚在上面被创建为空,请求尚未执行)。
稍后,从队列中提取请求,执行并接收响应。然后调用onResponse
,将response
添加到result
并打印出来。
欢迎使用多线程的世界:)