1. 程式人生 > >OKHttp get同步請求網路+post非同步請求網路+上傳圖片

OKHttp get同步請求網路+post非同步請求網路+上傳圖片

導依賴

    implementation 'com.squareup.okhttp3:okhttp:3.11.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'

 

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() {
        //log列印攔截
        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();
    }

    /**
     * 網路同步方法
     * 建立一個get請求
     * 設定一個路徑
     *
     * 通過mClient.newCall建一個Call物件
     * 呼叫同步請求方法
     *
     * @param url
     * @param callBack
     * @param clazz
     * @return
     * @throws IOException
     */
    public String getExecute(String url, final ICallBack callBack, final Class clazz) throws IOException {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();

        Call call = mClient.newCall(request);
        Response response = call.execute();
        return byte2String(response.body().bytes());
    }

    /**
     * 非同步的get方法
     * 建立一個請求
     * 建立一個call
     * 呼叫非同步請求
     *
     * @param url
     * @param callBack
     * @param clazz
     */
    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);
                    }
                });
            }
        });
    }

    /**
     * 建立非同步post方法
     * 建立表單FormBody
     * 把我們取出的key和value對應的放進去
     * 最後,build表單,生成RequestBody
     *
     * @param url 請求地址
     * @param params
     * @param clazz
     * @param callBack
     */
    public void postEnqueue(final String url, Map<String, String> params, final Class clazz, final ICallBack callBack) {
        FormBody.Builder builder = new FormBody.Builder();

        for (Map.Entry<String, String> entry : params.entrySet()) {
            builder.add(entry.getKey(), entry.getValue());
        }

        RequestBody body = builder.build();
        Request request = new Request.Builder()
                .post(body)
                .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();
                Gson gson = new Gson();
                final Object o = gson.fromJson(result, clazz);

                Log.i("dj", "----------------------------");
                Log.i("dj", "url is " + url);
                Log.i("dj", "result is " + result);
                Log.i("dj", "----------------------------");

                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callBack.success(o);
                    }
                });
            }
        });
    }

    /**
     * 上傳圖片
     * 建立MultipartBody.Builder,型別為Form
     * 如果上傳的是圖片
     * 通過File找到圖片
     * 給我們 MultipartBody.Builder新增一個表單資料
     * 第二個引數filename為上傳之後,伺服器儲存的名稱
     * 第三個引數建立requestBody,型別為表單資料
     * 第四個引數,檔案
     *
     * 如果遍歷發現不是檔案,則儲存普通鍵值對
     *
     * @param url
     * @param params
     * @param clazz
     * @param callBack
     */
    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(entry.getKey(), "圖片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);
                    }
                });
            }
        });
    }

    /**
     * 把流轉成字串 666版
     */
    private static String byte2String(byte[] bytes) {
        return new String(bytes);
    }
}

建立介面

public interface ICallBack {
    void success(Object obj);
    void failed(Exception e);
}