安卓网络请求库: Fast Android Networking

以下是Fast Android Networking优于它库的几个方面:

每个请求都可以轻易的定制OkHttpClient-比如超时等。

因为它使用了OkHttpClient和Okio,所以速度很快

支持RxJava

支持把JSON解析成java对象(同时支持Jackson解析)。

可以得到任何请求的详细数据分析。你可以知道发送了多少字节,接收了多少字节,以及请求所花的时间。这些数据是很重要的,这样你就可以识别出慢的请求。

你可以得到当前的带宽和网络质量以写出更合理的代码-网络质量高的时候下载高质量的图片,不好的时候下载低质量的图片。

Proper Response Caching— which leads toreduced bandwidth usage.

很好的响应请求-可以减少带宽的使用。

一个executor可以被传递给任何请求让响应在另一个线程中被获取。如果你在响应中做了很重的任务,你不可以在主线程中做。

一个库就能处理所有类型的网络问题-下载,上传,multipart。

可以通过设置prefetch(预取)让请求在需要的时候立即返回缓存。

任何类型的自定义都是可以的

立即请求真的是立即发生的。

很好的取消请求。

如果一个请求完成了指定的百分比,可以阻止其取消。

一个简单的接口就可以做任何类型的请求。

为什么你应该使用Fast Android Networking Library?

最近Android Marshmallow(Android M)上对HttpClient的移除让其它的网络库都过时了。

没有哪个单一的库做完了所有的事情,比如发送请求,下载任意类型的文件,上传文件,在ImageView中加载网络图片,等等。有一些库可以但是都过时了。

因为使用了sOkHttp,所以支持HTTP/2。

没有哪个库为网络中所有类型的事情提供了简单的接口,比如设置优先级,取消请求等。

如何使用Fast Android Networking:

build.gradle

   
   
   
   
  1. compile 'com.amitshekhar.android:android-networking:0.2.0'

如果和RxJava一起使用

   
   
   
   
  1. compile 'com.amitshekhar.android:rx-android-networking:0.1.0'

如果和Jackson Parser一起使用

   
   
   
   
  1. compile 'com.amitshekhar.android:jackson-android-networking:0.2.0'

别忘了加网络权限

   
   
   
   
  1.  android:name="android.permission.INTERNET" />

然后在application类的onCreate()方法中做初始化:

   
   
   
   
  1. AndroidNetworking.initialize(getApplicationContext());

 发起GET请求

   
   
   
   
  1. AndroidNetworking.get("http://api.localhost.com/{pageNumber}/test")

  2.                  .addPathParameter("pageNumber", "0")

  3.                  .addQueryParameter("limit", "3")

  4.                  .addHeaders("token", "1234")

  5.                  .setTag("test")

  6.                  .setPriority(Priority.LOW)

  7.                  .build()

  8.                  .getAsJSONArray(new JSONArrayRequestListener() {

  9.                     @Override

  10.                     public void onResponse(JSONArray response) {

  11.                     // do anything with response

  12.                     }

  13.                     @Override

  14.                     public void onError(ANError error) {

  15.                     // handle error

  16.                     }

  17.                 });

发起POST请求

   
   
   
   
  1. AndroidNetworking.post("http://api.localhost.com/createAnUser")

  2.                  .addBodyParameter("firstname", "Amit")

  3.                  .addBodyParameter("lastname", "Shekhar")

  4.                  .setTag("test")

  5.                  .setPriority(Priority.MEDIUM)

  6.                  .build()

  7.                  .getAsJSONArray(new JSONArrayRequestListener() {

  8.                     @Override

  9.                     public void onResponse(JSONArray response) {

  10.                     // do anything with response

  11.                     }

  12.                     @Override

  13.                     public void onError(ANError error) {

  14.                     // handle error

  15.                     }

  16.                 });

从服务器下载一个文件

    
    
    
    
  1. AndroidNetworking.download(url,dirPath,fileName)

  2.                  .setTag("downloadTest")

  3.                  .setPriority(Priority.MEDIUM)

  4.                  .build()

  5.                  .setDownloadProgressListener(new DownloadProgressListener() {

  6.                     @Override

  7.                     public void onProgress(long bytesDownloaded, long totalBytes) {

  8.                     // do anything with progress  

  9.                     }

  10.                  })

  11.                  .startDownload(new DownloadListener() {

  12.                     @Override

  13.                     public void onDownloadComplete() {

  14.                     // do anything after completion

  15.                     }

  16.                     @Override

  17.                     public void onError(ANError error) {

  18.                     // handle error    

  19.                     }

  20.                 });

上传一个文件

    
    
    
    
  1. AndroidNetworking.upload(url)

  2.                  .addMultipartFile("image",file)    

  3.                  .setTag("uploadTest")

  4.                  .setPriority(Priority.IMMEDIATE)

  5.                  .build()

  6.                  .setUploadProgressListener(new UploadProgressListener() {

  7.                     @Override

  8.                     public void onProgress(long bytesUploaded, long totalBytes) {

  9.                     // do anything with progress 

  10.                     }

  11.                  })

  12.                  .getAsJSONObject(new JSONObjectRequestListener() {

  13.                     @Override

  14.                     public void onResponse(JSONObject response) {

  15.                     // do anything with response                

  16.                     }

  17.                     @Override

  18.                     public void onError(ANError error) {

  19.                     // handle error 

  20.                     }

  21.                  });

得到一个响应并在另一个线程executor中完成

(注 : 错误和进度总是在主线程中返回)

    
    
    
    
  1. AndroidNetworking.upload(url)

  2.                  .addMultipartFile("image",file)    

  3.                  .setTag("uploadTest")

  4.                  .setPriority(Priority.IMMEDIATE)

  5.                  .build()

  6.                  .setExecutor(Executors.newSingleThreadExecutor()) // setting an executor to get response or completion on that executor thread

  7.                  .setUploadProgressListener(new UploadProgressListener() {

  8.                     @Override

  9.                     public void onProgress(long bytesUploaded, long totalBytes) {

  10.                     // do anything with progress 

  11.                     }

  12.                  })

  13.                  .getAsJSONObject(new JSONObjectRequestListener() {

  14.                     @Override

  15.                     public void onResponse(JSONObject response) {

  16.                     // below code will be executed in the executor provided

  17.                     // do anything with response                

  18.                     }

  19.                     @Override

  20.                     public void onError(ANError error) {

  21.                     // handle error 

  22.                     }

  23.                  });

  24. 和JAVA对象一起使用 - JSON Parser

       
       
       
       
  1. /*--------------Example One -> Getting the userList----------------*/

  2. AndroidNetworking.get("http://api.localhost.com/getAllUsers/{pageNumber}")

  3.                 .addPathParameter("pageNumber", "0")

  4.                 .addQueryParameter("limit", "3")

  5.                 .setTag(this)

  6.                 .setPriority(Priority.LOW)

  7.                 .build()

  8.                 .getAsParsed(new TypeToken<List<User>>() {}, new ParsedRequestListener<List<User>>() {

  9.                     @Override

  10.                     public void onResponse(List<User> users) {

  11.                     // do anything with response

  12.                     Log.d(TAG, "userList size : " + users.size());

  13.                     for (User user : users) {

  14.                         Log.d(TAG, "id : " + user.id);

  15.                         Log.d(TAG, "firstname : " + user.firstname);

  16.                         Log.d(TAG, "lastname : " + user.lastname);

  17.                     }

  18.                     }

  19.                     @Override

  20.                     public void onError(ANError anError) {

  21.                      // handle error

  22.                     }

  23.                 });

  24. /*--------------Example Two -> Getting an user----------------*/

  25. AndroidNetworking.get("http://api.localhost.com/getAnUser/{userId}")

  26.                 .addPathParameter("userId", "1")

  27.                 .setTag(this)

  28.                 .setPriority(Priority.LOW)

  29.                 .build()

  30.                 .getAsParsed(new TypeToken<User>() {}, new ParsedRequestListener<User>() {

  31.                      @Override

  32.                      public void onResponse(User user) {

  33.                      // do anything with response

  34.                          Log.d(TAG, "id : " + user.id);

  35.                          Log.d(TAG, "firstname : " + user.firstname);

  36.                          Log.d(TAG, "lastname : " + user.lastname);

  37.                      }

  38.                      @Override

  39.                      public void onError(ANError anError) {

  40.                       // handle error

  41.                      }

  42.                  }); 

  43. /*-- Note : TypeToken and getAsParsed is important here --*/



用ConnectionClass Listener得到当前网络质量和带宽

       
       
       
       
  1. // Adding Listener

  2. AndroidNetworking.setConnectionQualityChangeListener(new ConnectionQualityChangeListener() {

  3.             @Override

  4.             public void onChange(ConnectionQuality currentConnectionQuality, int currentBandwidth) {

  5.                 // do something on change in connectionQuality

  6.             }

  7.         });

  8.  

  9. // Removing Listener   

  10. AndroidNetworking.removeConnectionQualityChangeListener();

  11.  

  12. // Getting current ConnectionQuality

  13. ConnectionQuality connectionQuality = AndroidNetworking.getCurrentConnectionQuality();

  14. if(connectionQuality == ConnectionQuality.EXCELLENT){

  15. // do something

  16. }else if (connectionQuality == ConnectionQuality.POOR){

  17. // do something

  18. }else if (connectionQuality == ConnectionQuality.UNKNOWN){

  19. // do something

  20. }

  21. // Getting current bandwidth

  22. int currentBandwidth = AndroidNetworking.getCurrentBandwidth(); // Note : if (currentBandwidth == 0) : means UNKNOWN

取消一个请求

任何一个指定了tag的请求都可以被取消。

      
      
      
      
  1. AndroidNetworking.cancel("tag");

把从网络加载的图片放到ImageView

      
      
      
      
  1.       

  2.           android:id="@+id/imageView"

  3.           android:layout_width="100dp"

  4.           android:layout_height="100dp"

  5.           android:layout_gravity="center" />

  6.  

  7.       imageView.setDefaultImageResId(R.drawable.default);

  8.       imageView.setErrorImageResId(R.drawable.error);

  9.       imageView.setImageUrl(imageUrl);

从url获取指定了一些参数的Bitmap

      
      
      
      
  1. AndroidNetworking.get(imageUrl)

  2.                  .setTag("imageRequestTag")

  3.                  .setPriority(Priority.MEDIUM)

  4.                  .setBitmapMaxHeight(100)

  5.                  .setBitmapMaxWidth(100)

  6.                  .setBitmapConfig(Bitmap.Config.ARGB_8888)

  7.                  .build()

  8.                  .getAsBitmap(new BitmapRequestListener() {

  9.                     @Override

  10.                     public void onResponse(Bitmap bitmap) {

  11.                     // do anything with bitmap

  12.                     }

  13.                     @Override

  14.                     public void onError(ANError error) {

  15.                     // handle error

  16.                     }

  17.                 });

Prefetch a request (so that it can return from cache when required at instant)

      
      
      
      
  1. AndroidNetworking.get(ApiEndPoint.BASE_URL + ApiEndPoint.GET_JSON_ARRAY)

  2.                 .addPathParameter("pageNumber", "0")

  3.                 .addQueryParameter("limit", "30")

  4.                 .setTag(this)

  5.                 .setPriority(Priority.LOW)

  6.                 .build()

  7.                 .prefetch();

为某个请求自定义OkHttpClient

      
      
      
      
  1. OkHttpClient okHttpClient = new OkHttpClient().newBuilder()

  2.                 .addInterceptor(new GzipRequestInterceptor())

  3.                 .build();

  4.  

  5. AndroidNetworking.get("http://api.localhost.com/{pageNumber}/test")

  6.                  .addPathParameter("pageNumber", "0")

  7.                  .addQueryParameter("limit", "3")

  8.                  .addHeaders("token", "1234")

  9.                  .setTag("test")

  10.                  .setPriority(Priority.LOW)

  11.                  .setOkHttpClient(okHttpClient) // passing a custom okHttpClient 

  12.                  .build()

  13.                  .getAsJSONArray(new JSONArrayRequestListener() {

  14.                     @Override

  15.                     public void onResponse(JSONArray response) {

  16.                     // do anything with response

  17.                     }

  18.                     @Override

  19.                     public void onError(ANError error) {

  20.                     // handle error

  21.                     }

  22.                 });


Getting Analytics of a request by setting AnalyticsListener on that

      
      
      
      
  1. AndroidNetworking.download(url,dirPath,fileName)

  2.                  .setTag("downloadTest")

  3.                  .setPriority(Priority.MEDIUM)

  4.                  .build()

  5.                  .setAnalyticsListener(new AnalyticsListener() {

  6.                       @Override

  7.                       public void onReceived(long timeTakenInMillis, long bytesSent, long bytesReceived, boolean isFromCache) {

  8.                           Log.d(TAG, " timeTakenInMillis : " + timeTakenInMillis);

  9.                           Log.d(TAG, " bytesSent : " + bytesSent);

  10.                           Log.d(TAG, " bytesReceived : " + bytesReceived);

  11.                           Log.d(TAG, " isFromCache : " + isFromCache);

  12.                       }

  13.                   })

  14.                  .setDownloadProgressListener(new DownloadProgressListener() {

  15.                     @Override

  16.                     public void onProgress(long bytesDownloaded, long totalBytes) {

  17.                     // do anything with progress  

  18.                     }

  19.                  })

  20.                  .startDownload(new DownloadListener() {

  21.                     @Override

  22.                     public void onDownloadComplete() {

  23.                     // do anything after completion

  24.                     }

  25.                     @Override

  26.                     public void onError(ANError error) {

  27.                     // handle error    

  28.                     }

  29.                 }); 


你可能感兴趣的:(安卓网络请求库: Fast Android Networking)