gpt4 book ai didi

java - 如何异步接收来自Web的数据并在下一行代码中使用结果字符串?

转载 作者:行者123 更新时间:2023-12-01 12:55:25 24 4
gpt4 key购买 nike

我想从我的 API 获取一些 JSON 代码。我希望在 OnCreate 中执行类似的操作:

try
{
String jsonstr = getSomeThingAndPauseAndroid("http://someplace.com/api/xyz");
if (!jsonstr.isEmpty()) JSONObject jsonobj = new JSONObject(jsonstr);
}
catch { // handle error }

但是当这种情况发生时,Android 只是去做一些事情,而不是等待请求完成和响应,而我在 jsonstr 上什么也得不到。

有什么方法可以做到这一点而不需要大量新的类文件吗?

最佳答案

正确的方法是异步发出请求并在响应时触发方法。这是使用 Google Volley 的示例:

 //Start volley:
RequestQueue queue = Volley.newRequestQueue(this); // this = context


final String url = "http://someplace.com/api/xyz"";

// prepare the Request
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>()
{
@Override
public void onResponse(JSONObject response) {
//This is where you setup your UI
//Remember to dismiss the ProgressDialog
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
//Remember to dismiss the ProgressDialog
Log.d("Error.Response", response);
}
}
);

// add it to the RequestQueue
//Here you should add a ProgressDialog so the user knows to wait
queue.add(getRequest);

关于java - 如何异步接收来自Web的数据并在下一行代码中使用结果字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23957644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com