代码复用强,少写多余的代码+节省系统的资源(只有一个Client对象)
单例的gongju类:构造私有化+自行实例化+提供公开的方法
导依赖:
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
package com.example.day3_okhttp;
import android.util.Log;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
/**
* 1.单例模式工具类,保证只有一个OkhttpClient
* 构造私有化---自行实例化---公开方法
*
* */
public class OkhttpUtils {
private static OkHttpClient client;//只会有一个
private OkhttpUtils(){}
private static OkhttpUtils okhttpUtils=new OkhttpUtils();
public static OkhttpUtils getInstance(){//只会走一次
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.readTimeout(5, TimeUnit.SECONDS);
builder.callTimeout(5,TimeUnit.SECONDS);
//添加log拦截器
builder.addInterceptor(httpLoggingInterceptor);
//添加Token拦截器:为每个请求添加请求头
builder.addInterceptor(tokenInterceptor);
client=builder.build();
return okhttpUtils;
}
//log打印拦截器
static HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
Log.d("ytx", "log: "+message);
}
});
//token拦截器
static Interceptor tokenInterceptor=new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
// Request request = chain.request();//获得request杜希昂
// Request.Builder builder = request.newBuilder();
// builder.header("token","1704");//设置请求头
// Request request1 = builder.build();//创建新的request
Request request = chain.request().newBuilder().header("token", "1704").build();
return chain.proceed(request);
}
};
/***
*
* @param url 网址
* @param myCallback 回调的接口
*/
public void doget(String url, final MyCallback myCallback){
Request request = new Request.Builder()
.get()
.url(url)
.header("token","123")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback(