我使用异步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";
}
}
谢谢,
答案 0 :(得分:0)
不,这不是一个糟糕的方式。我建议使用Retrofit
,它将在后台线程上为您处理大部分样板网络内容,并在完成时通过回调为您提供响应。