拦截器:
//拦截器
public class MyInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Request newRequest = chain.request().newBuilder()
.addHeader("source", "android")
.url(request.url())
.build();
return chain.proceed(newRequest);
}
}
okhttp : 封装的post请求 (公共类):
public class OkHttpUtils {
private static volatile OkHttpUtils instance;
private OkHttpClient client;
private Handler handler = new Handler();
private OkHttpUtils() {
client = new OkHttpClient.Builder()
//设置拦截器
.addInterceptor(new MyInterceptor())
.build();
}
public static OkHttpUtils getInstance() {
if (null == instance) {
synchronized (OkHttpUtils.class) {
if (instance == null) {
instance = new OkHttpUtils();
}
}
}
return instance;
}
public void post(String url, Map<String, Object> map, final CallBack callBack, final Class cls) {
FormBody.Builder builder = new FormBody.Builder();
if (map != null && !map.isEmpty()) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
builder.add(entry.getKey(), (String) entry.getValue());
}
}
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() {
callBack.onFailed(e);
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
final Object o = GsonUtils.getInstance().fromJson(result, cls);
handler.post(new Runnable() {
@Override
public void run() {
callBack.onSuccess(o);
}
});
}
});
}
}
在P层: 防止内存泄漏:
//防止内存泄漏
public void detachView() {
if (null != iv) {
iv = null;
}
}
MainActivity(视图层)
@Override
protected void onDestroy() {
super.onDestroy();
if (presenter != null) {
//调用P层 防止内存泄漏
presenter.detachView();
}
}