我刚刚使用Okhttp制作了一个简单的JSON解析程序,现在什么是OKhttp响应中的回调以及为什么我们使用它?
OkHttpClient okHttpClient=new OkHttpClient();
Request request=new Request.Builder().url(url).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
答案 0 :(得分:2)
Callbacks are used for asynchronous calls, in this case it will either return you the result from your network call to the url(Json/Xml data) in onsuccess or if there is an error onfailure will be called.
Error could be if connection didn't got through or connection timeout, response timeout, resource/address not valid, etc.
答案 1 :(得分:0)
您已使用入队,这已将请求与其他队列一起放入了队列。与dobackground相同,将其从Mainthread中移除,并允许其他操作继续
回调是必需的,以便当网站有响应时,它知道使用了哪个请求,并通过回调将数据传回。
https://square.github.io/okhttp/3.x/okhttp/okhttp3/Callback.html