post请求路径不用加后面的参数,放入Map中就行,公共参数在拦截器中
拦截器:
public class MyInterCeptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); HttpUrl build = request.url().newBuilder().addQueryParameter("source", "android").build(); Request build1 = request.newBuilder().url(build).build(); return chain.proceed(build1); } }
OKHttpUtils:
public class OKHttpUtils { Handler handler = new Handler(); private static volatile OKHttpUtils okhttputils; public static OKHttpUtils getInstence(){ if(null==okhttputils){ synchronized (OKHttpUtils.class){ if(okhttputils==null){ okhttputils = new OKHttpUtils(); } } } return okhttputils; } public void post(String url, Map<String,String> map,final MView mview,final Class clas){ OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(new MyIntercapter()) .build(); FormBody.Builder builder = new FormBody.Builder(); if(map!=null&&!map.isEmpty()){ for(Map.Entry<String,String> entry:map.entrySet()){ builder.add(entry.getKey(),entry.getValue()); } } final Request request = new Request.Builder() .url(url) .post(builder.build()) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, final IOException e) { handler.post(new Runnable() { @Override public void run() { mview.onShibai(e); } }); } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); Gson gson = new Gson(); final Object o = gson.fromJson(string, clas); handler.post(new Runnable() { @Override public void run() { mview.onChenggong(o); } }); } }); } }
防止内存泄漏:
V层//判断new的P层为不为空,为空调用P层的销毁方法
protected void onDestroy() {
super.onDestroy();
if (presenter != null) {
presenter.detachView();
}
}
P层:
判断V层的接口为不为空,不为空变为空
public void detachView() {
if (null != iv) {
iv = null;
}
}