android Volley

Volley使用介紹

劉德政 Leander Liu 2020/07/23 10:10:20
50

 

壹、 Volley簡介

Volley是一個可讓Android應用網路通信套件。您可以在GitHub上獲取Volley

Volley 具有以下優勢:

自動調度網Request

併發連接。

可設置不同Request的優先順序。

可取消Request API。您可以取消單一Request,也可以設置要取消的時間段或範圍內的Request

可輕鬆自定義,例如自定義重試和退回時間。

預設即支持原始StringImageJSON

Volley不適用於下載大量內容的操作或Stream傳輸操作。

貳、 使用Volley

一、 前置作業

1.          權限宣告

<uses-permission android:name="android.permission.INTERNET" />

2.          設置依賴

dependencies {
      
       implementation 'com.android.volley:volley:1.1.1'
}

二、 設置流程

建立RequestQueue->建立Request->Request 加入到RequestQueue

1.          RequestQueue

RequestQueue用途

A.          基礎RequestQueue

RequestQueue requestQueue = Volley.newRequestQueue(context.getApplication());
requestQueue.add(request);

B.          自定義RequestQueue

    RequestQueue requestQueue;
    //初始化 cache
    Cache cache = new DiskBasedCache(getCacheDir(), 1024 * 1024); // 1MB cap
   
// 設置HttpURLConnection HTTP client network     Network network = new BasicNetwork(new HurlStack());
   
//cachenetwork 初始化 RequestQueue     requestQueue = new RequestQueue(cache, network);
   
// Start the queue     requestQueue.start();     String url ="http://www.example.com";
   
// 設置 request 及處理response.
 
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
     
@Override
     
public void onResponse(String response) {
         
// 處理 response
      }
  },
     
new Response.ErrorListener() {
         
@Override
         
public void onErrorResponse(VolleyError error) {
             
// 處理error
      }
  });
   
// 加入 request RequestQueue.
  requestQueue.add(stringRequest);
 
// ...  

2.          Request

Request用途

A.          基礎RequestStringRequestJsonObjectRequestJsonArrayRequestImageRequest

                                                            i.                StringRequest建構參數

參數:http methodAPI API請求參數、response 監聽器、error response 監聽器

StringRequest(int method, String url, Listener<String> listener, @Nullable ErrorListener errorListener)

                                                           ii.                JsonObjectRequest建構參數

參數:http methodAPI API請求參數、response 監聽器、error response 監聽器

JsonObjectRequest(int method,
       
String url,
       
@Nullable JSONObject jsonRequest,
       
Listener<JSONObject> listener,
       
@Nullable ErrorListener errorListener)

jsonRequest參數為null時,http methodGET,反之為POST,參數: API API請求參數、response 監聽器、error response 監聽器

JsonObjectRequest(  String url,
       
@Nullable JSONObject jsonRequest,
       
Listener<JSONObject> listener,
        
@Nullable ErrorListener errorListener)

                                                    iiiJsonArrayRequest建構參數

參數:API response 監聽器、error response 監聽器

JsonArrayRequest(String url, Listener<JSONArray> listener, @Nullable ErrorListener errorListener)

參數:http methodAPI API請求參數、response 監聽器、error response 監聽器

JsonArrayRequest( int method,
       
String url,
       
@Nullable JSONArray jsonRequest,
       
Listener<JSONArray> listener,
       
@Nullable ErrorListener errorListener)

                                                         iv.                ImageRequest建構參數

ImageRequest( String url,
       
Response.Listener<Bitmap> listener,
        int
maxWidth,
        int
maxHeight,
       
ScaleType scaleType,
       
Config decodeConfig,
       
@Nullable Response.ErrorListener errorListener)

B.          自定義Request

                                                            i.                設置headers

                                                           ii.                設置params

                                                         iii.                Response處理

繼承Request

public class GsonRequest<T> extends Request<T> {
        private final Gson gson = new Gson();
     
private final Class<T> clazz;
     
private final Map<String, String> headers;
     
private final Listener<T> listener;
       
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
             
Listener<T> listener, ErrorListener errorListener) {
         
super(Method.GET, url, errorListener);
         
this.clazz = clazz;
         
this.headers = headers;
         
this.listener = listener;
      }
       
@Override
     
public Map<String, String> getHeaders() throws AuthFailureError {
         
return headers != null ? headers : super.getHeaders();
      }
       
@Override
     
protected void deliverResponse(T response) {
          listener.onResponse(response);
      }
       
@Override
     
protected Response<T> parseNetworkResponse(NetworkResponse response) {
         
try {
             
String json = new String(
                      response.data,
                     
HttpHeaderParser.parseCharset(response.headers));
             
return Response.success(gson.fromJson(json, clazz),HttpHeaderParser.parseCacheHeaders(response));
          }
catch (UnsupportedEncodingException e) {
             
return Response.error(new ParseError(e));
          }
catch (JsonSyntaxException e) {
             
return Response.error(new ParseError(e));
          }
      }
  }

  3.          實作

自定義request串接api

public class CustomRequest extends JsonObjectRequest {
   private String token; /**GET建構子*/
public CustomRequest(String token, String url, Response.Listener<JSONObject> listener, @Nullable Response.ErrorListener errorListener) {
  
super(Request.Method.GET, url, null, listener, errorListener);
   this
.token = token;
}
/**POST建構子*/
public CustomRequest(String token, String url, @Nullable JSONObject jsonRequest, Response.Listener<JSONObject> listener, @Nullable Response.ErrorListener errorListener) {
  
super(Request.Method.POST, url, jsonRequest, listener, errorListener);
   this
.token = token;
}
/**添加Headers*/
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
   HashMap<String
,String> header = new HashMap<>();
  
header.put("Authorization","Bearer "+ token);
    return header;
} 建立自定義POT Reust物件

參數:TOKENAPI API參數、response監聽器、error response監聽器

CustomRequest customRequest = new CustomRequest(token, api, jsonObject, listener, errorListener);

建立自定義GET Request物件

參數:TOKENAPIresponse監聽器、error response監聽器

CustomRequest customRequest = new CustomRequest(token, api, listener, errorListener);

 Response監聽器

Response.Listener<JSONObject> listener = 
new Response.Listener<JSONObject>() {
   
@Override
   
public void onResponse(JSONObject response) {
              /*處理Response*/     }
}
;

 

/*加入RequestQueue*/
RequestQueue requestQueue = Volley.newRequestQueue(this.getApplication());
requestQueue.add(customRequest);

 

劉德政 Leander Liu