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

BaseOkHttp V3

Github

github.com/kongzue/Bas…html

BaseOkHttp Maven License Homepage

簡介

  • BaseOkHttp V3是基於BaseOkHttp V2( github.com/kongzue/Bas… )的升級版本,基於可以快速建立經常使用請求連接而封裝的庫。
  • 本庫中自帶 OkHttp 庫,並對其關聯的 okio 庫進行了包名的修改和封裝,所以不會影響到您項目中的其餘版本的 okHttp 庫,亦不會產生衝突。
  • 若請求來自於一個 Activity,結束請求後自動迴歸主線程操做,不須要再作額外處理。
  • 提供統一返回監聽器ResponseListener處理返回數據,避免代碼反覆臃腫。
  • 強大的全局方法和事件讓您的請求駕輕就熟。

Maven倉庫或Gradle的引用方式

Maven倉庫:git

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

Gradle:github

在dependencies{}中添加引用:express

implementation 'com.kongzue.baseokhttp_v3:baseokhttp_v3:3.0.2'
複製代碼

試用版能夠前往 fir.im/BaseOkHttp 下載apache

通常請求

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

以參數形式建立請求:bash

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);
複製代碼

或者也能夠以流式代碼建立請求:app

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;
相關文章
相關標籤/搜索