Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android 的OkHttp 網絡請求框架的學習封裝

Android 的OkHttp 網絡請求框架的學習封裝

編輯:關於Android編程

自述:在此以前,自己從來沒有寫過博客,今天是第一次寫,真心是有點小激動,正要下筆卻不知道應該從何說起,若是寫的不好,請各位見諒吧!關於網絡請求,我自認為自己是一個菜鳥,沒有任何經驗,之前做的項目都是別人封裝好,告訴我怎麼調用就好了。至於怎麼封裝邏輯的,真是一竅不通,可近來比較閒,就學習封裝了一下OkHttp 。

OkHttp分為同步和異步請求;請求方式常用的有 get和post兩種方式,封裝請求的大致步驟為:

1、首先 創建 一個mOkHttpClient = new OkHttpClient()對象;

2、構建Request請求對象(根據get和post不同的請求方式分別創建);

3、如果是 post請求還需要 構建 請求參數 Params,RequestBody requestBody = buildFormData(params); builder.post(requestBody).build;;

4、進行網絡異步請求mOkHttpClient.newCall(request).enqueue(new Callback() {} ),如果是同步請求,則改為 Response response = mOkHttpClient.newCall(request).execute()進行 ;

具體實現就不細說了,直接上代碼如下:

 

public class OkHttpManager {

    private static OkHttpManager mOkHttpManager;

    private OkHttpClient mOkHttpClient;

    private Gson mGson;

    private Handler handler;

    private OkHttpManager() {
        mOkHttpClient = new OkHttpClient();
        mOkHttpClient.newBuilder().connectTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS);
        mGson = new Gson();
        handler = new Handler(Looper.getMainLooper());
    }

    //創建 單例模式(OkHttp官方建議如此操作)
    public static OkHttpManager getInstance() {
        if (mOkHttpManager == null) {
            mOkHttpManager = new OkHttpManager();
        }
        return mOkHttpManager;
    }

    /***********************
     * 對外公布的可調方法
     ************************/

    public void getRequest(String url, final BaseCallBack callBack) {
        Request request = buildRequest(url, null, HttpMethodType.GET);
        doRequest(request, callBack);
    }

    public void postRequest(String url, final BaseCallBack callBack, Map params) {
        Request request = buildRequest(url, params, HttpMethodType.POST);
        doRequest(request, callBack);
    }

    public void postUploadSingleImage(String url, final BaseCallBack callback, File file, String fileKey, Map params) {
        Param[] paramsArr = fromMapToParams(params);

        try {
            postAsyn(url, callback, file, fileKey, paramsArr);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void postUploadMoreImages(String url, final BaseCallBack callback, File[] files, String[] fileKeys, Map params) {
        Param[] paramsArr = fromMapToParams(params);

        try {
            postAsyn(url, callback, files, fileKeys, paramsArr);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /***********************
     * 對內方法
     ************************/
    //單個文件上傳請求  不帶參數
    private void postAsyn(String url, BaseCallBack callback, File file, String fileKey) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, null);
        doRequest(request, callback);
    }

    //單個文件上傳請求 帶參數
    private void postAsyn(String url, BaseCallBack callback, File file, String fileKey, Param... params) throws IOException {
        Request request = buildMultipartFormRequest(url, new File[]{file}, new String[]{fileKey}, params);
        doRequest(request, callback);
    }

    //多個文件上傳請求 帶參數
    private void postAsyn(String url, BaseCallBack callback, File[] files, String[] fileKeys, Param... params) throws IOException {
        Request request = buildMultipartFormRequest(url, files, fileKeys, params);
        doRequest(request, callback);
    }

    //異步下載文件
    public void asynDownloadFile(final String url, final String destFileDir, final BaseCallBack callBack) {
        final Request request = buildRequest(url, null, HttpMethodType.GET);
        callBack.OnRequestBefore(request);  //提示加載框
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                callBack.onResponse(response);

                InputStream is = null;
                byte[] buf = new byte[1024*2];
                final long fileLength = response.body().contentLength();
                int len = 0;
                long readLength = 0;
                FileOutputStream fos = null;
                try {
                    is = response.body().byteStream();
                    File file = new File(destFileDir, getFileName(url));
                    fos = new FileOutputStream(file);
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        readLength += len;
                        int curProgress = (int) (((float) readLength / fileLength) * 100);
                        Log.e("lgz", "onResponse: >>>>>>>>>>>>>" + curProgress + ", readLength = " + readLength + ", fileLength = " + fileLength);
                        callBack.inProgress(curProgress, fileLength, 0);
                    }
                    fos.flush();
                    //如果下載文件成功,第一個參數為文件的絕對路徑
                    callBackSuccess(callBack, call, response, file.getAbsolutePath());
                } catch (IOException e) {
                    callBackError(callBack, call, response.code());
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                    }
                }
            }
        });


    }

    //構造上傳圖片 Request
    private Request buildMultipartFormRequest(String url, File[] files, String[] fileKeys, Param[] params) {
        params = validateParam(params);
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (Param param : params) {
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + param.key + "\""),
                    RequestBody.create(MediaType.parse("image/png"), param.value));
        }
        if (files != null) {
            RequestBody fileBody = null;
            for (int i = 0; i < files.length; i++) {
                File file = files[i];
                String fileName = file.getName();
                fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileName)), file);
                //TODO 根據文件名設置contentType
                builder.addPart(Headers.of("Content-Disposition",
                        "form-data; name=\"" + fileKeys[i] + "\"; filename=\"" + fileName + "\""),
                        fileBody);
            }
        }

        RequestBody requestBody = builder.build();
        return new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
    }

    //Activity頁面所有的請求以Activity對象作為tag,可以在onDestory()裡面統一取消,this
    public void cancelTag(Object tag) {
        for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
        for (Call call : mOkHttpClient.dispatcher().runningCalls()) {
            if (tag.equals(call.request().tag())) {
                call.cancel();
            }
        }
    }

    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = fileNameMap.getContentTypeFor(path);
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    private String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");
        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1, path.length());
    }

    private Param[] fromMapToParams(Map params) {
        if (params == null)
            return new Param[0];
        int size = params.size();
        Param[] res = new Param[size];
        Set> entries = params.entrySet();
        int i = 0;
        for (Map.Entry entry : entries) {
            res[i++] = new Param(entry.getKey(), entry.getValue());
        }
        return res;
    }

    //去進行網絡 異步 請求
    private void doRequest(Request request, final BaseCallBack callBack) {
        callBack.OnRequestBefore(request);
        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                callBack.onFailure(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                callBack.onResponse(response);
                String result = response.body().string();
                if (response.isSuccessful()) {

                    if (callBack.mType == String.class) {
//                        callBack.onSuccess(call, response, result);
                        callBackSuccess(callBack, call, response, result);
                    } else {
                        try {
                            Object object = mGson.fromJson(result, callBack.mType);//自動轉化為 泛型對象
//                            callBack.onSuccess(call, response, object);
                            callBackSuccess(callBack, call, response, object);
                        } catch (JsonParseException e) {
                            //json解析錯誤時調用
                            callBack.onEror(call, response.code(), e);
                        }

                    }
                } else {
                    callBack.onEror(call, response.code(), null);
                }

            }

        });


    }

    //創建 Request對象
    private Request buildRequest(String url, Map params, HttpMethodType methodType) {

        Request.Builder builder = new Request.Builder();
        builder.url(url);
        if (methodType == HttpMethodType.GET) {
            builder.get();
        } else if (methodType == HttpMethodType.POST) {
            RequestBody requestBody = buildFormData(params);
            builder.post(requestBody);
        }
        return builder.build();
    }

    //構建請求所需的參數表單
    private RequestBody buildFormData(Map params) {
        FormBody.Builder builder = new FormBody.Builder();
        builder.add("platform", "android");
        builder.add("version", "1.0");
        builder.add("key", "123456");
        if (params != null) {
            for (Map.Entry entry : params.entrySet()) {
                builder.add(entry.getKey(), entry.getValue());
            }
        }
        return builder.build();
    }

    private void callBackSuccess(final BaseCallBack callBack, final Call call, final Response response, final Object object) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callBack.onSuccess(call, response, object);
            }
        });

    }

    private void callBackError(final BaseCallBack callBack, final Call call, final int code) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                callBack.onEror(call, code, null);
            }
        });

    }

    private Param[] validateParam(Param[] params) {
        if (params == null)
            return new Param[0];
        else
            return params;
    }

    public static class Param {
        public Param() {
        }

        public Param(String key, String value) {
            this.key = key;
            this.value = value;
        }

        String key;
        String value;
    }

    enum HttpMethodType {
        GET, POST
    }


}
其中的 BaseCallBack回調機制封裝如下:

 

 

public abstract class BaseCallBack {
    public Type mType;

    static Type getSuperclassTypeParameter(Class subclass) {
        Type superclass = subclass.getGenericSuperclass();
        if (superclass instanceof Class) {
            throw new RuntimeException("Missing type parameter.");
        }
        ParameterizedType parameterized = (ParameterizedType) superclass;
        return $Gson$Types.canonicalize(parameterized.getActualTypeArguments()[0]);
    }


    public BaseCallBack() {
        mType = getSuperclassTypeParameter(getClass());
    }

    protected abstract void OnRequestBefore(Request request);

    protected abstract void onFailure(Call call, IOException e);

    protected abstract void onSuccess(Call call, Response response, T t);

    protected abstract void onResponse(Response response);

    protected abstract void onEror(Call call, int statusCode, Exception e);

    protected abstract void inProgress(int progress, long total , int id);
}

 

上面這個類OkHttpManager 是我根據網絡上各家資源學習封裝好的,copy進代碼可以直接使用,並且根據okhttp3.0以後的版本,對之前的一下請求參數設置進行了最新的修改,具體如下:

1、設置請求超時參數;

okhttp3.0以前的版本是這樣設置的

new OkHttpClient();

mHttpClient.setConnectTimeout(10, TimeUnit.SECONDS);

mHttpClient.setReadTimeout(10,TimeUnit.SECONDS);

mHttpClient.setWriteTimeout(30,TimeUnit.SECONDS);

之後的版本是這樣設置的:

new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT,TimeUnit.SECONDS)//設置讀取超時時間
.writeTimeout(WRITE_TIMEOUT,TimeUnit.SECONDS)//設置寫的超時時間
.connectTimeout(CONNECT_TIMEOUT,TimeUnit.SECONDS)//設置連接超時時間

2、post方式請求時,構建表單對象參數;

okhttp3.0以前的版本是這樣構建的:new FormEncodingBuilder()對象,然後向裡面add (key,value)參數;

之後的版本更改為:FormBody body = new FormBody.Builder(),.add(key, value);即是FormEncodingBuilder已被FormBody取代;

至於BaseCallBack類,根據請求數據的功能的不同,還需要對此進行封裝,集成自己需要的方法實現;

一、進行一般的數據加載請求,可直接調用如下:

模擬用戶登錄:

 

 Map params = new HashMap();
                    params.put("Mobile", username.getText().toString());
                    params.put("PassWord", password.getText().toString());

                    OkHttpManager.getInstance().postRequest(Constants.LOGIN_URL, new LoadCallBack(getActivity()) {
                                @Override
                                protected void onSuccess(Call call, Response response, String s) {
                                    Log.e("lgz", "onSuccess = " + s);
                                    Toast.makeText(getActivity(), "登錄成功!", Toast.LENGTH_LONG).show();
                                }

                                @Override
                                protected void onEror(Call call, int statusCode, Exception e) {
                                    Log.e("lgz", "Exception = " + e.toString());
                                }
                            }
                            , params);

上面登錄請求中 就用到了自己根據需要再次封裝的Callback類的繼承實現,LoadCallBack類:

 

 

//添加對請求時對話框的處理
public abstract class LoadCallBack extends BaseCallBack {
    private Context context;
    private SpotsDialog spotsDialog;

    public LoadCallBack(Context context) {
        this.context = context;
        spotsDialog = new SpotsDialog(context);
    }

    private void showDialog() {
        spotsDialog.show();
    }

    private void hideDialog() {
        if (spotsDialog != null) {
            spotsDialog.dismiss();
        }
    }

    public void setMsg(String str) {
        spotsDialog.setMessage(str);
    }

    public void setMsg(int  resId) {
        spotsDialog.setMessage(context.getString(resId));
    }


    @Override
    protected void OnRequestBefore(Request request) {
        showDialog();

    }

    @Override
    protected void onFailure(Call call, IOException e) {
        hideDialog();
    }

    @Override
    protected void onResponse(Response response) {
        hideDialog();
    }

    @Override
    protected void inProgress(int progress, long total, int id) {

    }
其實這個類就是對BaseCallBack再次繼承實現;

 

二、下載文件,並顯示進度條對話框的請求操作:

下載一張圖片:

 

OkHttpManager.getInstance().asynDownloadFile("http://www.7mlzg.com/uploads/bwf_1477419976.jpg", FILE_PATH, new FileCallBack(getActivity()) {
                    @Override
                    protected void onResponse(Response response) {

                    }

                    @Override
                    protected void onSuccess(Call call, Response response, String s) {
                        super.onSuccess(call, response, s);
                        Log.e("lgz", "status = : " + s);
                        Toast.makeText(getActivity(), "下載成功", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                        Uri uri = Uri.fromFile(new File(s));//廣播通知系統圖集更新
                        intent.setData(uri);
                        getActivity().sendBroadcast(intent);
                    }
                });

上面下載圖片中,就用到了自己根據需要再次繼承Callback類封裝得到的FileCallBack類如下:

 

 

public abstract class FileCallBack extends BaseCallBack {

    private Context mContext;

    private ProgressDialog mProgressDialog;

    public FileCallBack(Context context) {
        mContext = context;
        initDialog();
    }

    private void initDialog(){
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setTitle("下載中...");
        mProgressDialog.setCanceledOnTouchOutside(true);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setMax(100);
    }

    private void hideDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void OnRequestBefore(Request request) {
        mProgressDialog.show();
    }

    @Override
    protected void onFailure(Call call, IOException e) {
       hideDialog();
    }

    @Override
    protected void onSuccess(Call call, Response response, T t) {
        Log.e("lgz", "onSuccess: >>>>>>>>>>>>>");
        hideDialog();
    }

    @Override
    protected void onEror(Call call, int statusCode, Exception e) {
        hideDialog();
    }

    @Override
    protected void inProgress(int progress, long total, int id) {
        Log.e("lgz", "inProgress: >>>>>>>>>>>>>"+progress);
        mProgressDialog.setProgress(progress);

    }
}

 

 

三、最後說一下使用okhttp的配置:

在Android Studio 中,直接在build.gradle文件裡配置 :compile 'com.squareup.okhttp3:okhttp:3.4.1'

在Eclipse裡需要導入jar包使用,下載最新jar;


當然了,這裡只是對Okhttp常用的一些功能進行了封裝處理,使用的都是異步請求方式,至於同步操作,我個人覺得不是很常用,使用時需要開啟一個線程,不然會阻塞UI線程的;最後,這只是一個簡單的學習,其中要是有不足和錯誤,還希望大家留言批評指正,謝謝!

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved