使用AsyncTask和OkHttp实现异步网络请求
AsyncTask底层使用线程池+Handler的方式,实现异步请求,对Handler做了一层封装,可以在doInBackground方法中执行耗时操作,比如网络请求,在onPostExecute执行更新UI的操作。因此,可以使用一个接口回调到调用其方法的Activity中,更新UI。
其中AsyncTask的三个参数分别为传入参数、进度、执行结果
实现如下:
public class HttpAsyncTaskHelper extends AsyncTask<String,Integer,String> {
private AsyncHttpRequestListener listener;
public HttpAsyncTaskHelper(AsyncHttpRequestListener listener) {
this.listener = listener;
}
@Override
protected String doInBackground(String... strings) {
OkHttpClient client=new OkHttpClient();
Request request=new Request.Builder().url(strings[0]).build();
try {
Response response=client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
return e.toString();
}
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
listener.onSuccess(s);
}
}
在Activity中调用执行即可
private void updateWeatherInfoUseAsyncTask(String link){
HttpAsyncTaskHelper helper=new HttpAsyncTaskHelper(new AsyncHttpRequestListener() {
@Override
public void onSuccess(String result) {
WeatherBean weatherBean= SearchResultParser.parseData(result);
Log.i("onSuccess",weatherBean.getData().toString());
parseData(weatherBean);//解析数据,更新UI
}
@Override
public void onFailed(String reason) {
}
});
helper.execute(link);
}