【发布时间】:2015-03-10 20:38:37
【问题描述】:
我正在使用异步 Okhttp 进行请求,然后使用响应来填充 UI。
我的想法是在主线程中等待响应,然后开始一个新的活动。这是最好的方法吗?如果是这样,我如何在主线程中等待和访问响应的解析数据?
主要活动:
public void sendMessage(View view) throws IOException, InterruptedException {
Intent intent = new Intent(this, DisplayMessageActivity.class);
...
HttpHelper client = new HttpHelper();
String response = client.get("https://www.google.com");
...
intent.putExtra(EXTRA_MESSAGE, message+"\nresponse:\n"+response);
Bundle b = new Bundle();
b.putStringArray("DATA_GET", client.dataOut);
intent.putExtras(b);
startActivity(intent);
}
HttpHelper 类:
public class HttpHelper {
OkHttpClient client = new OkHttpClient();
String[] dataOut;
String get(String url) throws IOException, InterruptedException {
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Response response) throws IOException{
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
// parsing response
dataOut = ...;
}
});
return "done";
}
}
谢谢,
【问题讨论】:
标签: android asynchronous okhttp