1. 程式人生 > >[Android]Kongzue.BaseOkHttpV3 - 一款很好上手的BaseOkHttp封裝

[Android]Kongzue.BaseOkHttpV3 - 一款很好上手的BaseOkHttp封裝

BaseOkHttp V3

Github

github.com/kongzue/Bas…

BaseOkHttp Maven License Homepage

簡介

  • BaseOkHttp V3是基於BaseOkHttp V2( github.com/kongzue/Bas… )的升級版本,基於能夠快速建立常用請求連結而封裝的庫。
  • 本庫中自帶 OkHttp 庫,並對其關聯的 okio 庫進行了包名的修改和封裝,因此不會影響到您專案中的其他版本的 okHttp 庫,亦不會產生衝突。
  • 若請求來自於一個 Activity,結束請求後自動迴歸主執行緒操作,不需要再做額外處理。
  • 提供統一返回監聽器ResponseListener處理返回資料,避免程式碼反覆臃腫。
  • 強大的全域性方法和事件讓您的請求得心應手。

Maven倉庫或Gradle的引用方式

Maven倉庫:

<dependency>
  <groupId>com.kongzue.baseokhttp_v3</groupId>
  <artifactId>baseokhttp_v3</artifactId>
  <version>3.0.2</version>
  <type>pom</type>
</dependency>
複製程式碼

Gradle:

在dependencies{}中新增引用:

implementation 'com.kongzue.baseokhttp_v3:baseokhttp_v3:3.0.2'
複製程式碼

試用版可以前往 fir.im/BaseOkHttp 下載

一般請求

BaseOkHttp V3 提供兩種請求寫法,範例如下:

以引數形式建立請求:

progressDialog = ProgressDialog.show(context, "請稍候", "請求中...");
HttpRequest.POST(context, "http://你的介面地址", new Parameter().add("page", "1"), new ResponseListener
() { @Override public void onResponse(String response, Exception error) { progressDialog.dismiss(); if (error == null) { resultHttp.setText(response); } else { resultHttp.setText("請求失敗"); Toast.makeText(context, "請求失敗", Toast.LENGTH_SHORT).show(); } } }); 複製程式碼

一般請求中,使用 HttpRequest.POST(...) 方法可直接建立 POST 請求,相應的,HttpRequest.GET(...) 可建立 GET 請求,另外可選額外的方法增加 header 請求頭:

HttpRequest.POST(Context context, String url, Parameter headers, Parameter parameter, ResponseListener listener);
HttpRequest.GET(Context context, String url, Parameter headers, Parameter parameter, ResponseListener listener);
複製程式碼

或者也可以以流式程式碼建立請求:

progressDialog = ProgressDialog.show(context, "請稍候", "請求中...");
HttpRequest.build(context,"http://你的介面地址")
        .addHeaders("Charset", "UTF-8")
        .addParameter("page", "1")
        .addParameter("token", "A128")
        .setResponseListener(new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("請求失敗");
                    Toast.makeText(context, "請求失敗", Toast.LENGTH_SHORT).show();
                }
            }
        })
        .doPost();
複製程式碼

返回回撥監聽器只有一個,請在其中對 error 引數判空,若 error 不為空,則為請求失敗,反之則為請求成功,請求成功後的資料存放在 response 引數中。

之所以將請求成功與失敗放在一個回撥中主要目的是方便無論請求成功或失敗都需要執行的程式碼,例如上述程式碼中的 progressDialog 等待對話方塊都需要關閉(dismiss掉),這樣的寫法更為方便。

Json請求

有時候我們需要使用已經處理好的json文字作為請求引數,此時可以使用 HttpRequest.JSONPOST(...) 方法建立 json 請求。

json 請求中,引數為文字型別,建立請求方式如下:

progressDialog = ProgressDialog.show(context, "請稍候", "請求中...");
HttpRequest.JSONPOST(context, "http://你的介面地址", "{\"key\":\"DFG1H56EH5JN3DFA\",\"token\":\"124ASFD53SDF65aSF47fgT211\"}", new ResponseListener() {
    @Override
    public void onResponse(String response, Exception error) {
        progressDialog.dismiss();
        if (error == null) {
            resultHttp.setText(response);
        } else {
            resultHttp.setText("請求失敗");
            Toast.makeText(context, "請求失敗", Toast.LENGTH_SHORT).show();
        }
    }
});
複製程式碼

Json請求中,可使用 HttpRequest.JSONPOST(...) 快速建立 Json 請求,另外可選額外的方法增加 header 請求頭:

HttpRequest.JSONPOST(Context context, String url, Parameter headers, String jsonParameter, ResponseListener listener)
複製程式碼

也可以使用流式程式碼建立請求:

progressDialog = ProgressDialog.show(context, "請稍候", "請求中...");
HttpRequest.build(context,"http://你的介面地址")
        .setJsonParameter("{\"key\":\"DFG1H56EH5JN3DFA\",\"token\":\"124ASFD53SDF65aSF47fgT211\"}")
        .setResponseListener(new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("請求失敗");
                    Toast.makeText(context, "請求失敗", Toast.LENGTH_SHORT).show();
                }
            }
        })
        .doPost();
複製程式碼

Json請求只能以 POST 的方式進行,如果執行doGet(); 方法也會以 POST 的方式發出。

檔案上傳

要使用檔案上傳就需要將 File 型別的檔案作為引數傳入 Parameter,此時引數中亦可以傳入其他文字型別的引數。

一旦引數傳入檔案,請求必然為 POST 型別,即便呼叫了 HttpRequest.GET(...) 也會當作 POST 型別的請求發出。

範例程式碼如下:

progressDialog = ProgressDialog.show(context, "請稍候", "請求中...");
HttpRequest.POST(context, "http://你的介面地址", new Parameter()
                         .add("key", "DFG1H56EH5JN3DFA")
                         .add("imageFile1", file1)
                         .add("imageFile2", file2)
        , new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("請求失敗");
                    Toast.makeText(context, "請求失敗", Toast.LENGTH_SHORT).show();
                }
            }
        });
複製程式碼

也可以使用流式程式碼建立請求:

HttpRequest.build(context,"http://你的介面地址")
        .addHeaders("Charset", "UTF-8")
        .addParameter("page", "1")
        .addParameter("imageFile1", file1)
        .addParameter("imageFile2", file2)
        .setResponseListener(new ResponseListener() {
            @Override
            public void onResponse(String response, Exception error) {
                progressDialog.dismiss();
                if (error == null) {
                    resultHttp.setText(response);
                } else {
                    resultHttp.setText("請求失敗");
                    Toast.makeText(context, "請求失敗", Toast.LENGTH_SHORT).show();
                }
            }
        })
        .doPost();
複製程式碼

預設上傳檔案使用的 mediaType 為 "image/png",可使用以下程式碼進行修改:

.setMediaType(MediaType.parse("application/pdf"))       //設定為pdf型別
複製程式碼

型別參考如下:

內容 含義
text/html HTML格式
text/plain 純文字格式
text/xml XML格式
image/gif gif圖片格式
image/jpeg jpg圖片格式
image/png png圖片格式
application/xhtml+xml XHTML格式
application/xml XML資料格式
application/atom+xml Atom XML聚合格式
application/json JSON資料格式
application/pdf pdf格式
application/msword Word文件格式
application/octet-stream 二進位制流資料
multipart/form-data 表單資料

額外功能

全域性日誌

全域性日誌開關(預設是關閉態,需要手動開啟):

BaseOkHttp.DEBUGMODE = true;
複製程式碼

BaseOkHttp V3支援增強型日誌,使用輸出日誌內容是 json 字串時,會自動格式化輸出,方便檢視。

BaseOkHttp Logs

在您使用 BaseOkHttp 時可以在 Logcat 的篩選中使用字元 “>>>” 對日誌進行篩選(Logcat日誌介面上方右側的搜尋輸入框)。

您可以在 Android Studio 的 File -> Settings 的 Editor -> Color Scheme -> Android Logcat 中調整各型別的 log 顏色,我們推薦如下圖方式設定顏色:

Kongzue's log settings

全域性請求地址

設定全域性請求地址後,所有介面都可以直接使用相對地址進行,例如設定全域性請求地址:

BaseOkHttp.serviceUrl = "https://www.example.com";
複製程式碼

發出一個請求:

HttpRequest.POST(context, "/femaleNameApi", new Parameter().add("page", "1"), new ResponseListener() {...});
複製程式碼

那麼實際請求地址即 www.example.com/femaleNameA… ,使用更加輕鬆方便。

全域性 Header 請求頭

使用如下程式碼設定全域性 Header 請求頭:

BaseOkHttp.overallHeader = new Parameter()
        .add("Charset", "UTF-8")
        .add("Content-Type", "application/json")
        .add("Accept-Encoding", "gzip,deflate")
;
複製程式碼

全域性請求返回攔截器

使用如下程式碼可以設定全域性返回資料監聽攔截器,return true 可返回請求繼續處理,return false 即攔截掉不會繼續返回原請求進行處理;

BaseOkHttp.responseInterceptListener = new ResponseInterceptListener() {
    @Override
    public boolean onResponse(Context context, String url, String response, Exception error) {
        if (error != null) {
            return true;
        } else {
            Log.i("!!!", "onResponse: " + response);
            return true;
        }
    }
};
複製程式碼

HTTPS 支援

  1. 請將SSL證書檔案放在assets目錄中,例如“ssl.crt”;
  2. 以附帶SSL證書名的方式建立請求:
BaseOkHttp.SSLInAssetsFileName = "ssl.crt";
...
複製程式碼

即可使用Https請求方式。

另外,可使用 BaseOkHttp.httpsVerifyServiceUrl=(boolean) 設定是否校驗請求主機地址與設定的 HttpRequest.serviceUrl 一致;

全域性引數攔截器

使用如下程式碼可以設定全域性引數監聽攔截器,此引數攔截器可以攔截並修改、新增所有請求攜帶的引數。

此方法亦適用於需要對引數進行加密的場景:

BaseOkHttp.parameterInterceptListener = new ParameterInterceptListener() {
    @Override
    public Parameter onIntercept(Parameter parameter) {
        parameter.add("key", "DFG1H56EH5JN3DFA");
        parameter.add("sign", makeSign(parameter.toParameterString()));
        return parameter;
    }
};

private String makeSign(String parameterString){
    //加密邏輯
    ...
}
複製程式碼

請求超時

使用以下程式碼設定請求超時時間(單位:秒)

BaseOkHttp.TIME_OUT_DURATION = 10;
複製程式碼

開源協議

Copyright Kongzue BaseOkHttp

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
複製程式碼

本專案中使用的網路請求底層框架為square.okHttp3(github.com/square/okht… ),感謝其為開源做出的貢獻。

相關協議如下:

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
複製程式碼

更新日誌

v3.0.2:

  • 日誌新增列印請求頭;
  • 日誌請求引數列印增強;
    BaseOkHttp Logs2.0
  • 修改完善了 OkHttplient 建立方式以及預設未設定證書時對 HTTPS 的驗證忽略;
  • 修復了檔案上傳的相關 bug;

v3.0.1:

  • 修復了一些bug;