Android開源:Http/Https 組件

Warran 7年前發布 | 13K 次閱讀 HTTP 安卓開發 Android開發 移動開發 HTTPS

android-major-https

android-major-https是一款 Android 上的 Http/Https 組件。內部使用 Volley 作為底層 Http 組件。主要特性有:

  • 支持 GET、 POST、 DELETE、 PUT、 HEAD 等;
  • 支持 Http、 Https
  • 對 Https 支持 自定義證書驗證域名驗證 等;
  • 支持 Text、 Binary、 Json、 文件下載、 文件上傳等;
  • 支持 Json 自動解析為 POJO;
  • 接口簡潔易用,支持 Java8 Lambda

1、Gradle 配置

compile 'com.jungle.majorhttp:major-http:1.0.0'

2、使用方法

使用預定義的各種 Model 來加載 URL,通過各種方法來設置加載參數。最后使用 load loadWithProgress 來加載請求。

load只是在后臺加載,界面上沒有任何表現。 loadWithProgress 在加載的時候會彈出一個加載展示 Dialog(該對話框樣式可自定義),并在后臺加載。請求返回后,將自動關閉 Dialog。

預定義的 Model 列表如下:

請求類型 Model 數據結果
文本請求 TextRequestModel String
Json POJO 請求 JsonRequestModel POJO Java 對象
二進制數據請求 BinaryRequestModel byte[]
數據下載(獲取)請求 DownloadRequestModel byte[]
文件下載請求 DownloadFileRequestModel String 下載好的文件路徑
上傳請求 UploadRequestModel String 服務器返回的上傳結果
JsonObject 請求 JsonObjectRequestModel JSONObject
JsonArray 請求 JsonArrayRequestModel JSONArray

具體代碼示例如下:

private static final String DEMO_WEB_URL =
        "

private static final String DEMO_JSON_URL = "

private static final String DEMO_UPLOAD_URL = "

private void showError(int errorCode, String message) { // ... }</code></pre>

TextRequestModel
        .newModel()
        .url(DEMO_WEB_URL)
        .success(new ModelSuccessListener<String>() {
            @Override
            public void onSuccess(NetworkResp networkResp, String response) {
                TextViewerActivity.start(getContext(), response);
            }
        })
        .error(new ModelErrorListener() {
            @Override
            public void onError(int errorCode, String message) {
                showError(errorCode, message);
            }
        })
        .load();

或者只用一個統一的 Listener:

TextRequestModel
        .newModel()
        .url(DEMO_WEB_URL)
        .load(new ModelListener<String>() {
            @Override
            public void onSuccess(NetworkResp networkResp, String response) {
                TextViewerActivity.start(getContext(), response);
            }

        @Override
        public void onError(int errorCode, String message) {
            showError(errorCode, message);
        }
    });</code></pre> 

如果你支持 Java8 ,你還可以使用 lambda 表達式。可以看出使用 lambda 后,整個語法簡潔了很多:

TextRequestModel
        .newModel()
        .url(DEMO_WEB_URL)
        .success((networkResp, response) -> TextViewerActivity.start(getContext(), response))
        .error(this::showError)
        .load();
  • Json POJO 請求,使用 JsonRequestModel
public class GithubUserInfo {

    public static class Project {
        public String name;
        public String url;
    }

    public String uid;
    public String userName;
    public String site;
    public String[] languages;
    public List<Project> projects;
}

JsonRequestModel
        .newModel(GithubUserInfo.class)
        .url(DEMO_JSON_URL)
        .method(ModelMethod.GET)
        .load(new BizModelListener<GithubUserInfo>() {
            @Override
            public void onSuccess(NetworkResp networkResp, GithubUserInfo response) {
                String info = JSON.toJSONString(response, SerializerFeature.PrettyFormat);
                info = "Load Json object success!\n\n" + info;
                TextViewerActivity.start(getContext(), info);
            }

            @Override
            public void onError(int errorCode, String message) {
                showError(errorCode, message);
            }
        });

Json 解析為 POJO 的過程,使用第三方 Json 庫 fastjson

  • 文件下載請求,使用 DownloadFileRequestModel
final String file = getDemoFilePath();
String loadingText = String.format("Downloading File: \n%s", file);

DownloadFileRequestModel
        .newModel()
        .url(DEMO_JSON_URL)
        .filePath(file)
        .lifeListener(new ModelLoadLifeListener<DownloadFileRequestModel>() {
            @Override
            public void onBeforeLoad(DownloadFileRequestModel model) {
                ActivityCompat.requestPermissions(context,
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);
            }
        })
        .loadWithProgress(getContext(), loadingText, new BizModelListener<String>() {
            @Override
            public void onSuccess(NetworkResp networkResp, String response) {
                Toast.makeText(getContext(), String.format(
                        "Download file SUCCESS! file = %s.", file), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int errorCode, String message) {
                showError(errorCode, message);
            }
        });
  • 文件上傳請求,使用 UploadRequestModel
final String file = getDemoFilePath();

UploadRequestModel
        .newModel()
        .url(DEMO_UPLOAD_URL)
        .addFormItem(file)
        .loadWithProgress(this, "Uploading...", new BizModelListener<String>() {
            @Override
            public void onSuccess(NetworkResp networkResp, String response) {
                Toast.makeText(getContext(), String.format(
                        "Upload file SUCCESS! file = %s.", file), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(int errorCode, String message) {
                showError(errorCode, message);
            }
        });

3、Http / Https 支持

通過 MajorHttpClient 這個組件可以配置 Http / Https:

方法 解釋
setRequestQueueFactory 設置請求隊列 Factory
setDefaultTimeoutMilliseconds 設置基礎請求的超時時間
setUploadTimeoutMilliseconds 設置上傳類請求的超時時間
setExtraHeadersFiller 為每個請求設置額外的 Header 填充回調(具體項目中比如動態填入 uid、ticket 等等)

3.1、Http 支持

MajorHttpClient.getDefault().setRequestQueueFactory(new HttpRequestQueueFactory(context));

3.2、Https 支持

String[] certs = {
        "zhihu.cer",
        "github.cer",
        "githubusercontent.cer"
};

String[] domains = {
        "zhihu.com",
        "github.com",
        "githubusercontent.com"
};

HttpsRequestQueueFactory factory = new HttpsRequestQueueFactory(this, certs);
factory.setHostnameVerifier(new HttpsUtils.DomainHostnameVerifier(domains));

MajorHttpClient.getDefault().setRequestQueueFactory(factory);

Https 可以將證書文件放在 assets 文件夾下,或者放在 res/raw 文件夾下,然后在代碼中創建相應的 HttpsRequestQueueFactory 。通過 HttpsRequestQueueFactory.setHostnameVerifier 可以設置域名驗證。

3.3、Https 驗證失敗異常

如果請求的 URL 證書驗證 不通過,則錯誤如下:

com.android.volley.NoConnectionError:
    javax.net.ssl.SSLHandshakeException:
        java.security.cert.CertPathValidatorException:
            Trust anchor for certification path not found..

如果請求的 URL 域名驗證 不通過,則錯誤如下:

com.android.volley.NoConnectionError:
    javax.net.ssl.SSLPeerUnverifiedException: Hostname github.com not verified:
            certificate: sha1/1O6dKmcSs2FMJy0ViwT8yMoIoLY=
            DN: CN=github.com,O=GitHub\, Inc.,L=San Francisco,ST=California,C=US,2.5.4.17=#13053934313037,STREET=88 Colin P Kelly\, Jr Street,2.5.4.5=#130735313537353530,1.3.6.1.4.1.311.60.2.1.2=#130844656c6177617265,1.3.6.1.4.1.311.60.2.1.3=#13025553,2.5.4.15=#0c1450726976617465204f7267616e697a6174696f6e
            subjectAltNames: [github.com, www.github.com].

License

/**
 * Android Jungle-Major-Http framework project.
 *
 * Copyright 2016 Arno Zhang <zyfgood12@163.com>
 *
 * 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.
 */

 

 

 

 本文由用戶 Warran 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!