OkHttp的簡單使用以及使用單例模式新增日誌攔截器
阿新 • • 發佈:2018-11-19
okhttp的簡單使用,主要包含:
一般的get請求
一般的post請求
基於Http的檔案上傳
檔案下載
載入圖片
支援請求回撥,直接返回物件、物件集合
支援session的保持
//新增依賴
implementation 'com.squareup.okhttp3:okhttp:3.11.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0' //攔截日誌
import android.util.Log; import java.io.IOException; import java.util.concurrent.TimeUnit; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; /** * date:2018/11/16 * author:QMY(QMY) * function: */ public class OkHttpUtils{ public void requestData(String s) { //日誌攔截 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.e("msg", "++++++++" + message); } }); logging.setLevel(HttpLoggingInterceptor.Level.BODY); //建立okhttp物件 OkHttpClient okHttpClient = new OkHttpClient.Builder() .readTimeout(10, TimeUnit.SECONDS) .connectTimeout(10, TimeUnit.SECONDS) .addInterceptor(logging) .build(); //建立request final Request request = new Request.Builder() .url(s) .build(); //建立call okHttpClient.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { String string = response.body().string(); } }); } //單例模式 public class Singleton {//懶漢式 private volatile Singleton singleton; private Singleton() {} public Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } } }