//拦截器
private static Interceptor getAppInterceptor(){
Interceptor interceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.i("aaa","-----------"+"拦截前");
Response response = chain.proceed(request);
Log.i("aaa","-----------"+"拦截后");
return response;
}
};
return interceptor;
}
//设置单例
public static OKHttpMap getInstance(){
if(instance==null){
synchronized (OKHttpMap.class){
if(instance==null){
instance = new OKHttpMap();
}
}
}
return instance;
}
//封装get请求
public void doGet(String url, final Class clazz, final NetCallBack netCallBack){
OkHttpClient build = new OkHttpClient().newBuilder().addInterceptor(getAppInterceptor()).build();
Request request = new Request.Builder().url(url).get().build();
build.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String s = response.body().string();
handler.post(new Runnable() {
@Override
public void run() {
netCallBack.onSuccess(s);
}
});
}
});
}
//封装post请求
public static void doPost(String url, Map<String,String> map, final Class clazz, final NetCallBack netCallBack){
//不是FormBody,而是一个Builder
FormBody.Builder body = new FormBody.Builder();
//key value
for (String key:map.keySet()){
//value的值
body.add(key,map.get(key));
}
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(getAppInterceptor()).build();
Request request = new Request.Builder().url(url).post(body.build()).build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
netCallBack.onFailed(e);
}
@Override
public void onResponse(Call call, Response response) throws IOException {
final String s = response.body().string();
Log.i("sss", "run: "+s.toString());
final Object o = new Gson().fromJson(s, clazz);
handler.post(new Runnable() {
@Override
public void run() {
netCallBack.onSuccess(o);
}
});
}
});
}
//创建一个接口
public interface NetCallBack{
void onSuccess(Object o);
void onFailed(Exception e);
}