private static volatile HttpUtils instance; private OkHttpClient client; private Handler handler = new Handler(); private HttpUtils() { client = new OkHttpClient(); } public static HttpUtils getInstance() { if (instance == null) { synchronized (HttpUtils.class) { if (null == instance) { instance = new HttpUtils(); } } } return instance; }
ok
public void get(String url, final ICallBack callBack, final Type type) { Request builder = new Request.Builder() .get() .url(url) .build(); Call call = client.newCall(builder); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { callBack.onFailed(e); } }); } @Override public void onResponse(final Call call, Response response) throws IOException { String s = response.body().string(); Gson gson = new Gson(); final Object o = gson.fromJson(s, type); handler.post(new Runnable() { @Override public void run() { callBack.onSuccess(o); } }); } }); }
//model
public void login(String url, ICallBack iCallBack, Type type){ HttpUtils.getInstance().get(url,iCallBack,type); }
//p
private IView iv; private LoginModel loginModel; public void attach(IView iv){ this.iv = iv; loginModel = new LoginModel(); }
//回收
@Override
protected void onDestroy() {
super.onDestroy();
if (presenter != null) {
presenter.detach();
}
}