public class OkHttpUtils {
private OkHttpClient okHttpClient;
private static OkHttpUtils instance;
//单例模式
public static OkHttpUtils getInstance() {
if (instance==null){
synchronized (OkHttpUtils.class){
if (instance==null){
instance=new OkHttpUtils();
}
}
}
return instance;
}
//私有的构造方法
private OkHttpUtils(){
//日志拦截器
HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
okHttpClient=new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addNetworkInterceptor(interceptor)
.writeTimeout(5,TimeUnit.SECONDS)
.readTimeout(5,TimeUnit.SECONDS)
.connectTimeout(5,TimeUnit.SECONDS)
.build();
}
//post请求
public void doPost(String path, HashMap<String,String>map,final OkHttpCallBack okHttpCallBack){
FormBody.Builder builder = new FormBody.Builder();
for (Map.Entry<String, String> p : map.entrySet()) {
builder.add(p.getKey(),p.getValue());
}
Request request=new Request.Builder()
.url(path)
.post(builder.build())
.build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
if (okHttpCallBack!=null){
okHttpCallBack.failure("网络异常");
}
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String result = response.body().string();
if (okHttpCallBack!=null){
okHttpCallBack.success(result);
}
}
});
}
//取消网络请求
public void cancle(){
if (okHttpClient!=null){
okHttpClient.dispatcher().cancelAll();
}
}
}