Android okhttp3 框架请求连接等异步操作
自定义回调接口:
public interface MyOkhttp3Callback {
/**
* Called when the request could not be executed due to cancellation, a connectivity problem or
* timeout. Because networks can fail during an exchange, it is possible that the remote server
* accepted the request before the failure.
*/
void onFailure(Exception e);
void onResponse(String htmlString);
}
网络请求:
private void getAsyncOkHttp3Callback(final String urlStr, MyOkhttp3Callback callback) {
try {
//1.声名okhttp客户端
OkHttpClient okHttpClient = new OkHttpClient();
//2.设置请求方式,设置请求参数
Request request = new Request.Builder().get().url(urlStr).build();
//注意区别,同步是这样的:okHttpClient.newCall(request).execute();
okHttpClient.newCall(request).enqueue(new Callback() {
//异步
@Override //请求数据失败的回调
public void onFailure(Call call, IOException e) {
callback.onFailure(e);
}
@Override //请求数据成功的回调,子线程中运行的 可以判断下状态码 response.code()
public void onResponse(Call call, Response response) throws IOException {
byte[] bytes = response.body().bytes();//获得byte[]
if (bytes.length == 0 || bytes == null) {
//根据byte数组长度为0判断
callback.onFailure(new Exception("获取结果为空"));
} else {
String responseStr= new String(bytes, "UTF-8");
callback.onResponse(responseStr);
}
}
});
} catch (Exception e) {
Log.e("getAsyncOkHttp3", " getAsyncOkHttp has Exception:" + e.getMessage());
callback.onFailure(e);
}
}
调用如下
getAsyncOkHttp3Callback(urlStr, new MyOkhttp3Callback() {
@Override
public void onFailure(Exception e) {
// TODO 失败后相关提示或展示
}
//请求成功执行的方法
@Override
public void onResponse(String response) {
// 异步调用的回调函数是在子线程当中的,因为需要用Handler或者runOnUiThread来更新UI
xxxActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO 成功后获取数据进一步操作
}
});
}
});