天天看點

網絡架構-NoHttp NoHttp 使用方法 權限 NoHttp特性 一. 請求 二. 檔案上傳 三. 下載下傳檔案 四. 緩存模式 五. 取消請求 六. 自定義請求類型: FastJsonRequest 七. 混淆 License

NoHttp

NoHttp,一個有情懷的架構。
網絡架構-NoHttp NoHttp 使用方法 權限 NoHttp特性 一. 請求 二. 檔案上傳 三. 下載下傳檔案 四. 緩存模式 五. 取消請求 六. 自定義請求類型: FastJsonRequest 七. 混淆 License

如果你想用OkHttp,請看這個項目:NoHttp4OkHttp。

技術交流群:547839514,加群請一定閱讀群行為規範。

嚴振傑的首頁:www.yanzhenjie.com 嚴振傑的部落格:blog.yanzhenjie.com

使用方法

  • Eclipse使用Jar包,如果需要依賴源碼,請自行下載下傳。
    下載下傳Jar包
  • AndroidStudio使用Gradle建構添加依賴(推薦)
compile 'com.yolanda.nohttp:nohttp:1.0.7'      

權限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />      

NoHttp特性

  NoHttp實作了Http1.1(RFC2616),一個标準的Http架構。

  • 請求和下載下傳都是隊列,平均配置設定每個線程的資源,支援多個請求并發。
  • 支援GET、POST、PUT、PATCH、HEAD、DELETE、OPTIONS、TRACE等請求協定。
  • 支援基于POST、PUT、PATCH、DELETE的檔案上傳(Html表單原理)。
  • 檔案下載下傳、上傳下載下傳、上傳和下載下傳的進度回調、錯誤回調。
  • 提供了五種資料緩存政策供開發者選擇使用(詳細看下文)。
  • 支援取消某個請求、取消指定多個請求、取消所有請求。
  • 支援自定義Request,利用NoHttp泛型可以解析成你想要的任何資料格式(String、Json、JavaBean等)。
  • 支援Session、Cookie的自動維持,App重新開機、關開機後還持續維持。
  • 支援Https、自簽名網站Https的通路、支援雙向驗證。

友好的調試模式

  NoHttp提供了調試模式,打開後可以清晰的看到請求過程、怎麼傳遞資料等,基本不用抓包。可以看到請求頭、請求資料、響應頭、Cookie等的過程。你也不用擔心Log太多會讓你眼花缭亂,想象不到的整潔。

請求

  • 支援請求String、Json、FastJson、Gson、Bitmap、JavaBean、XML等擴充。
  • 異步請求,拿到結果直接更新UI,支援同步請求。

多檔案上傳

  所有下載下傳均有進度回調、錯誤回調等友好的接口。

  • 大檔案上傳,不會發生OOM。
  • 多檔案上傳,多個key多個檔案,一個key多個檔案(

    List<File>

    )。
  • 支援File、InputStream、ByteArray、Bitmap,實作NoHttp的Binary接口,理論上任何東西都可以傳。
  • 支援取消上傳。

檔案下載下傳

  • 檔案下載下傳,支援多個檔案同時下載下傳,并且有進度回調、錯誤回調等。
  • 支援暫停繼續下載下傳,支援取消下載下傳,支援斷點續傳。
  • 利用NoHttp的多檔案下載下傳可以做一個下載下傳管理器。

緩存模式

  • 僅僅請求網絡。
  • 僅僅讀取緩存。
  • 标準Http協定緩存(比如響應碼是304的情況),需要伺服器支援,如果伺服器不支援就和普通請求一樣。
  • 先請求網絡,請求失敗後傳回緩存。
  • 先讀取緩存,緩存不存在再請求網絡。

取消請求

  所有取消都支援正在執行的請求。

  • 支援取消某個請求。
  • 支援取消用sign指定的幾個請求。
  • 支援取消所有的請求。

請求自動維持Cookie

  • 支援Session、Cookie、臨時Cookie的維持。
  • 支援App重新開機、關機開機後繼續持久化維持。
  • 提供了接口,允許開發者監聽Cookie的變化,也可以改變某個Cookie的值。

重定向

  • 對于Http301、302、303、307等重定向的支援。
  • 支援多級重定向嵌套。
  • 支援禁用重定向、NoHttp提供了操作重定向的接口。

代理

  • 标準的Java的Api,ProXy:指定代理的IP和Port。
  • 比如調試時代理到自己電腦進行抓包,比如用代理通路Google。

一. 請求

String請求

// String 請求對象
Request<String> request = NoHttp.createStringRequest(url, requestMethod);
      

Json請求

// JsonObject
Request<JSONObject> request = NoHttp.createJsonObjectRequest(url, reqeustMethod);
...
// JsonArray
Request<JSONArray> request = NoHttp.createJsonArrayRequest(url, reqeustMethod);      

Bitmap請求

Request<Bitmap> request = NoHttp.createImageRequest(url, requestMethod);      

添加參數

Request<JSONObject> request = ...
request.add("name", "yoldada");// String類型
request.add("age", 18);// int類型
request.add("sex", '0')// char類型
request.add("time", 16346468473154); // long類型
...      

添加到隊列

RequestQueue requestQueue = NoHttp.newRequestQueue();
// 或者傳一個并發值,允許三個請求同時并發
// RequestQueue requestQueue = NoHttp.newRequestQueue(3);

// 發起請求
requestQueue.add(what, request, responseListener);      

  上面添加到隊列時有一個what,這個what會在

responseLisetener

響應時回調給開發者,是以我們可以用一個

responseLisetener

接受多個請求的響應,用what來區分結果。而不用像有的架構一樣,每一個請求都要new一個回調。

同步請求

  在目前線程發起請求,線上程這麼使用。

Request<String> request = ...
Response<String> response = NoHttp.startRequestSync(request);
if (response.isSucceed()) {
    // 請求成功
} else {
    // 請求失敗
}      

二. 檔案上傳

  支援多檔案上傳,多個key多個檔案,一個key多個檔案(

List<File>

)。支援File、InputStream、ByteArray、Bitmap,實作NoHttp的Binary接口,理論上任何東西都可以傳。

單個檔案

Request<String> request = ...
request.add("file", new FileBinary(file));      

上傳多個檔案、多個Key多個檔案形式

  這裡可以添加各種形式的檔案,File、Bitmap、InputStream、ByteArray:

Request<String> request = ...
request.add("file1", new FileBinary(File));
request.add("file2", new FileBinary(File));
request.add("file3", new InputStreamBinary(InputStream));
request.add("file4", new ByteArrayBinary(byte[]));
request.add("file5", new BitmapBinary(Bitmap));      

上傳多個檔案、一個Key多個檔案形式

  用同一個key添加,如果請求方法是POST、PUT、PATCH、DELETE,同一個key不會被覆寫。

Request<String> request = ...
fileList.add("image", new FileBinary(File));
fileList.add("image", new InputStreamBinary(InputStream));
fileList.add("image", new ByteArrayBinary(byte[]));
fileList.add("image", new BitmapBinary(Bitmap));      

  或者:

Request<String> request = ...

List<Binary> fileList = ...
fileList.add(new FileBinary(File));
fileList.add(new InputStreamBinary(InputStream));
fileList.add(new ByteArrayBinary(byte[]));
fileList.add(new BitmapStreamBinary(Bitmap));
request.add("file_list", fileList);      

三. 下載下傳檔案

  因為下載下傳檔案代碼比較多,這裡貼關鍵部分,具體的請參考sample。

發起下載下傳請求

//下載下傳檔案
downloadRequest = NoHttp.createDownloadRequest...
// what 區分下載下傳
// downloadRequest 下載下傳請求對象
// downloadListener 下載下傳監聽
downloadQueue.add(0, downloadRequest, downloadListener);      

暫停或者停止下載下傳

downloadRequest.cancel();      

監聽下載下傳過程

private DownloadListener downloadListener = new DownloadListener() {
    @Override
    public void onStart(int what, boolean resume, long preLenght, Headers header, long count) {
        // 下載下傳開始
    }

    @Override
    public void onProgress(int what, int progress, long downCount) {
        // 更新下載下傳進度
    }

    @Override
    public void onFinish(int what, String filePath) {
        // 下載下傳完成
    }

    @Override
    public void onDownloadError(int what, StatusCode code, CharSequence message) {
        // 下載下傳發生錯誤
    }

    @Override
    public void onCancel(int what) {
        // 下載下傳被取消或者暫停
    }
};      

四. 緩存模式

1. Http标準協定的緩存,比如響應碼是304時

  NoHttp本身是實作了RFC2616,是以這裡不用設定或者設定為DEFAULT。

Request<JSONObject> request = NoHttp.createJsonObjectRequest(url);
request.setCacheMode(CacheMode.DEFAULT);      

2. 當請求伺服器失敗的時候,讀取緩存

  請求伺服器成功則傳回伺服器資料,如果請求伺服器失敗,讀取緩存資料傳回。

Request<JSONObject> request = NoHttp.createJsonObjectRequest(url);
request.setCacheMode(CacheMode.REQUEST_NETWORK_FAILED_READ_CACHE);      

3. 如果發現有緩存直接成功,沒有緩存才請求伺服器

  我們知道ImageLoader的核心除了記憶體優化外,剩下一個就是發現把内地有圖檔則直接使用,沒有則請求伺服器,是以NoHttp這一點非常使用做一個ImageLoader。   如果沒有緩存才去請求伺服器,否則使用緩存:

Request<JSONObject> request = NoHttp.createJsonObjectRequest(url);
// 非标準Http協定,改變緩存模式為IF_NONE_CACHE_REQUEST_NETWORK
request.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST_NETWORK);      

  請求圖檔,緩存圖檔:

Request<Bitmap> request = NoHttp.createImageRequest(imageUrl);
request.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST_NETWORK);      

4. 僅僅請求網絡

  這裡不會讀取緩存,也不會使用Http304:

Request<Bitmap> request = NoHttp.createImageRequest(imageUrl);
request.setCacheMode(CacheMode.ONLY_REQUEST_NETWORK);
...      

5. 僅僅讀取緩存

  僅僅讀取緩存,不會請求網絡和其它操作:

Request<Bitmap> request = NoHttp.createImageRequest(imageUrl);
request.setCacheMode(CacheMode.ONLY_READ_CACHE);      

五. 取消請求

取消單個請求

  直接調用請求對象的cancel方法。

request.cancel();      

從隊列中取消指定的請求

  給請求set一個sign,取消的時候調用隊列的cancelBySign就可以取消掉所有指定這個sign的請求。

request.setCancelSign(sign);
...
queue.cancelBySign(sign);      

取消隊列中所有請求

queue.cancelAll();      

停止隊列

  隊列停止後再添加請求到隊列後,請求不會被執行。

RequestQueue queue = NoHttp.newRequestQueue();
...
queue.stop();      

六. 自定義請求類型: FastJsonRequest

定義請求對象

public class FastJsonRequest extends RestRequestor<JSONObject> {

    public FastJsonRequest(String url) {
        this(url, RequestMethod.GET);
    }

    public FastJsonRequest(String url, RequestMethod requestMethod) {
        super(url, requestMethod);
        setAccept("application/json");
    }

    @Override
    public JSONObject parseResponse(String url, Headers headers, byte[] responseBody) {
        String result = StringRequest.parseResponseString(url, headers, responseBody);
        JSONObject jsonObject = null;
        if (!TextUtils.isEmpty(result)) {
            jsonObject = JSON.parseObject(result);
        } else {
            // 這裡預設的錯誤可以定義為你們自己的資料格式
            jsonObject = JSON.toJSON("{}");
        }
        return jsonObject;
    }
}      

b. 使用自定義請求-和NoHttp預設請求沒有差別的哦

Request<JSONObject> mRequest = new FastJsonRequest(url, requestMethod);
queue.add(what, mRequest, responseListener);      

七. 混淆

需要知道的

  1. NoHttp全部的類都可以混淆。
  2. 1.0.1及以上所有版本使用了反射調用了進階或者低級的api,所有版本的build-tools都可以編譯。

如果你非要keep

-dontwarn com.yolanda.nohttp.**
-keep class com.yolanda.nohttp.**{*;}
           

License

Copyright 2016 Yan Zhenjie

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.                        

摘自:https://github.com/yanzhenjie/NoHttp


        

Android學習交流群:523487222

(如果您覺得有用,歡迎加入,一起學習進步) 點選連結加入群【Android學習群】

網絡架構-NoHttp NoHttp 使用方法 權限 NoHttp特性 一. 請求 二. 檔案上傳 三. 下載下傳檔案 四. 緩存模式 五. 取消請求 六. 自定義請求類型: FastJsonRequest 七. 混淆 License

繼續閱讀