1. 程式人生 > >關於OkHttp工具類的使用

關於OkHttp工具類的使用

/**

  • 靜態內部類單例模式

  • OKHttp的重點

  • 1:同步和非同步的區別

  • 2:get和POST怎麼使用

  • 3:怎麼封裝

  • 擴充套件有攔截器,上傳圖片,原始碼區看一看
    */
    public class OkUtils {
    private OkHttpClient okHttpClient;

    private OkUtils() {
    //日誌攔截器
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
    okHttpClient = new OkHttpClient.Builder()
    .connectTimeout(20, TimeUnit.SECONDS)
    .readTimeout(20, TimeUnit.SECONDS)
    .callTimeout(20, TimeUnit.SECONDS)
    .addInterceptor(loggingInterceptor)
    .build();
    }
    //使用單列模式
    public static OkUtils getInstance() {
    return OkHolder.okUtils;
    }

    static class OkHolder {
    private static final OkUtils okUtils = new OkUtils();
    }

    //這是同步的get和post
    public String getSync(String url) throws IOException {
    Request request = new Request.Builder().url(url).build();
    return okHttpClient.newCall(request).execute().body().string();
    }

    public String postSync(String url, String key, String value) throws IOException {
    RequestBody body = new FormBody.Builder().add(key, value).build();
    Request request = new Request.Builder().url(url).post(body).build();
    return okHttpClient.newCall(request).execute().body().string();
    }

    //非同步的get和post

    public void getAsync(String url, Callback callback) {
    Request request = new Request.Builder().url(url).build();
    okHttpClient.newCall(request).enqueue(callback);
    }

    public void postAsync(String url, Callback callback) {
    RequestBody body = new FormBody.Builder().add(“key”, “value”).build();
    Request request = new Request.Builder().url(url).post(body).build();
    okHttpClient.newCall(request).enqueue(callback);
    }

    //上傳圖片 必須是POST
    public void upLoadImage(String url, String uid, Callback callback) {
    File file = new File(Environment.getExternalStorageDirectory() + “/Pictures/test.jpg”);
    //上傳圖片需要 MultipartBody
    MultipartBody.Builder body = new MultipartBody.Builder().setType(MultipartBody.FORM)
    .addFormDataPart(“uid”, uid)
    .addFormDataPart(“file”, “test.jpg”, RequestBody.create(MediaType.parse(“image/jpg”), file));
    RequestBody body1 = body.build();
    Request request = new Request.Builder().url(url).post(body1).build();
    okHttpClient.newCall(request).enqueue(callback);

    }

}