okHttp的而二次封裝,單例模式
阿新 • • 發佈:2019-02-10
import android.os.Environment; import java.io.File; import java.io.IOException; import java.util.Map; import java.util.concurrent.TimeUnit; import okhttp3.Cache; import okhttp3.Call; import okhttp3.Callback; import okhttp3.FormBody; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; /** * Created by mamiaomiao on 2018/2/27. */ public class OkhttpUtil { private static OkhttpUtil util; private OkhttpUtil() { } public OkhttpUtil getInstance() { if (util == null) { synchronized (OkhttpUtil.class) { if (util == null) { util = new OkhttpUtil(); } } } return util; } private static OkHttpClient okHttpClient; private static OkHttpClient getOkHttpClient() { if (okHttpClient == null) { File sdcache = new File(Environment.getExternalStorageDirectory(), "cache"); int cacheSize = 10 * 1024 * 1024; okHttpClient = new OkHttpClient.Builder() .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); Request builder = request.newBuilder().addHeader("source", "android").build(); Response response = chain.proceed(builder); return response; } }) .connectTimeout(15, TimeUnit.SECONDS) //.cache(new Cache(sdcache, cacheSize)) .build(); } return okHttpClient; } /** * get請求 * 引數1 url * 引數2 回撥Callback */ public static void doGet(String url, Callback callback) { //建立OkHttpClient請求物件 OkHttpClient okHttpClient = getOkHttpClient(); //建立Request Request request = new Request.Builder().url(url).build(); //得到Call物件 Call call = okHttpClient.newCall(request); //執行非同步請求 call.enqueue(callback); } /** * post請求 * 引數1 url * 引數2 回撥Callback */ public static void doPost(String url, Map<String, String> params, Callback callback) { //建立OkHttpClient請求物件 OkHttpClient okHttpClient = getOkHttpClient(); //3.x版本post請求換成FormBody 封裝鍵值對引數 FormBody.Builder builder = new FormBody.Builder(); //遍歷集合 for (String key : params.keySet()) { builder.add(key, params.get(key)); } //建立Request Request request = new Request.Builder().url(url).post(builder.build()).build(); Call call = okHttpClient.newCall(request); call.enqueue(callback); } }