1. 程式人生 > >工具類封裝

工具類封裝

HttpUtils

package wanghuiqi.bawie.com.whq_yk_moni1.utils;

import android.os.Handler;
import android.os.Looper;

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

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpUtils {
    private final Handler handler;
    private OkHttpClient httpClient;
    private static HttpUtils mHttpUtils;

    private HttpUtils() {
        //建立主執行緒的handler
        handler = new Handler(Looper.getMainLooper());
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(5000, TimeUnit.MILLISECONDS)
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .writeTimeout(5000, TimeUnit.MILLISECONDS)
                .build();
    }

    //單例模式
    public static HttpUtils getInstance() {

        if (mHttpUtils == null) {
            synchronized (HttpUtils.class) {
                if (mHttpUtils == null) {
                    return mHttpUtils = new HttpUtils();
                }
            }
        }
        return mHttpUtils;
    }

    //建立介面
    public interface OKhttpInterface {
        void Failed(Exception e);

        void Success(String data);
    }

    public void doGet(String url, final OKhttpInterface moKhttpInterface) {
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (moKhttpInterface != null) {
                    //切換到主執行緒
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            moKhttpInterface.Failed(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response != null && response.isSuccessful()) {
                        final String data = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (moKhttpInterface != null) {
                                    moKhttpInterface.Success(data);
                                    return;
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

Post請求

    public void doPost(String url, Map<String, String> map, final OKhttpInterface mOkhttp) {
        //建立formBody的物件,把表單新增到formBody中
        FormBody.Builder builder = new FormBody.Builder();
        if (map != null) {
            for (String key : map.keySet()) {
                builder.add(key, map.get(key));
            }
        }
        FormBody formBody = builder.build();
        //建立request物件
        Request request = new Request.Builder()
                .post(formBody)
                .url(url)
                .build();
        //建立Call物件
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                if (httpClient != null) {
                    //切換到主執行緒
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            mOkhttp.Failed(e);
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    if (response != null && response.isSuccessful()) {
                        final String data = response.body().string();
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (mOkhttp != null) {
                                    mOkhttp.Success(data);
                                    return;
                                }
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (mOkhttp != null) {
                    mOkhttp.Failed(new Exception("網路異常"));
                }
            }
        });
    }
}