调查OKHttp并希望尽可能使用文档声明:“它支持同步阻塞调用和带回调的异步调用”。
但是如何设置回调,或者在收到响应后需要执行一大块代码?我在他们的网站上找不到任何东西。
我应该将呼叫嵌套到Async
线程中,如:
AsyncTask.execute(new Runnable() {
@Override
public void run() {
//TODO your background code
答案 0 :(得分:2)
来自样本
Request request = new Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build();
client.newCall(request).enqueue(new Callback() {
@Override public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
Headers responseHeaders = response.headers();
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
}
}
});