public class HttpHelper {
private final OkHttpClient mOkHttpClient;
//用单例来写这个请求工具类 饿汉式 懒汉式
private HttpHelper() {
mOkHttpClient = new OkHttpClient();
}
// static HttpHelper sHttpHelper = new HttpHelper();
static HttpHelper sHttpHelper;
public static HttpHelper getInstance() {
if (sHttpHelper == null) {
synchronized (HttpHelper.class) {
if (sHttpHelper == null) {
sHttpHelper = new HttpHelper();
}
}
}
return sHttpHelper;
}
//提供一个方法来进行网络请求
public void requestForAsyncGET(String url, final StringCallback stringCallback){
//请求数据 OKHttp
//1 OKHttpClient 在构造方法中去创建,不必创建多次了
//2 Request
Request request = new Request.Builder().url(url).build();
//3 Call
Call call = mOkHttpClient.newCall(request);
//4 call.enqueue 异步
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, final IOException e) {
Log.e(getClass().getSimpleName()+" xmg", "onFailure: "+e);
//自己得接口的失败方法
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
@Override
public void run() {
stringCallback.onFail(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if(!response.isSuccessful()){
onFailure(call,new IOException("响应失败"));
return;
}
//xxxooo
//自己得接口的成功方法
final String string = response.body().string();
/*Handler handler = new Handler();//handler当中的Looper是当前子线程中的looper*/
Handler handler = new Handler(Looper.getMainLooper());//handler当中的Looper是主线程中的looper
handler.post(new Runnable() {
@Override
public void run() {
stringCallback.onSuccess(string);
}
});
}
});
}
}
接口
public interface StringCallback {
void onFail(IOException e);
void onSuccess(String result);
}
Android网络请求利用第三方框架okHttp的工具类
最新推荐文章于 2024-07-18 17:04:34 发布