1. 程式人生 > >簡單封裝了一個OKHttp的工具類 非同步get請求和post請求

簡單封裝了一個OKHttp的工具類 非同步get請求和post請求

package com.example.okhttp.OkHttp;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.example.okhttp.Constants;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;

public class OkHttpUtils {
private static volatile OkHttpUtils mInstance;

private OkHttpClient mClient;

private Handler mHandler = new Handler(Looper.getMainLooper());

/**
 * 第一步,寫一個單例,這裡用的懶漢式,也可以使用餓漢
 * @return
 */
public static OkHttpUtils getInstance() {
    if (mInstance == null) {
        synchronized (OkHttpUtils.class) {
            if (null == mInstance) {
                mInstance = new OkHttpUtils();
            }
        }
    }
    return mInstance;
}

/**
 * 完成構造方法,OkHttpClient
 */
private OkHttpUtils() {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

    /**
     * 使用構造者模式
     * 設定連線超時
     * 讀取超時
     * 寫超時
     * 新增攔截器
     */
    mClient = new OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .addInterceptor(interceptor)
            .build();
}

public void getEnqueue(final String url, final ICallBack callBack, final Class clazz) {
    Request request = new Request.Builder()
            .get()
            .url(url)
            .build();
    Call call = mClient.newCall(request);
    call.enqueue(new Callback() {
        //網路請求連線失敗
        @Override
        public void onFailure(Call call, final IOException e) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callBack.failed(e);
                }
            });
        }
        //網路請求連線成功
        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String result = response.body().string();
            Log.i("dj", "----------------------------");
            Log.i("dj", "url is " + url);
            Log.i("dj", "result is " + result);
            Log.i("dj", "----------------------------");
            Gson gson = new Gson();
            final Object o = gson.fromJson(result, clazz);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callBack.success(o);
                }
            });
        }
    });
}

public void uploadImage(String url, Map<String, String> params, final Class clazz, final ICallBack callBack) {
    OkHttpClient okHttpClient = new OkHttpClient();
    MultipartBody.Builder builder = new MultipartBody.Builder()
            .setType(MultipartBody.FORM);

    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (entry.getKey().equals(Constants.MAP_KEY_UP_LOAD_IMG)) {
            File file = new File(entry.getValue());
            builder.addFormDataPart("file", "圖片1.png",
                    RequestBody.create(MediaType.parse("multipart/form-data"), file));
        }else{
            builder.addFormDataPart(entry.getKey(), entry.getValue());
        }
    }

    RequestBody requestBody = builder.build();

    final Request request = new Request.Builder()
            .url(url)
            .post(requestBody)
            .build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            e.printStackTrace();
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            String result = response.body().string();
            Gson gson = new Gson();
            final Object o = gson.fromJson(result, clazz);
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    callBack.success(o);
                }
            });
        }
    });
}

}