• <td id="ae6ms"><li id="ae6ms"></li></td>
  • <xmp id="ae6ms"><td id="ae6ms"></td><table id="ae6ms"></table>
  • <table id="ae6ms"></table>
  • <td id="ae6ms"></td>
    <td id="ae6ms"></td>
  • <table id="ae6ms"></table><table id="ae6ms"><td id="ae6ms"></td></table>
  • <td id="ae6ms"></td>
  • <table id="ae6ms"><li id="ae6ms"></li></table>
  • <table id="ae6ms"></table>
    西西軟件園多重安全檢測下載網站、值得信賴的軟件下載站!
    軟件
    軟件
    文章
    搜索

    首頁編程開發Android → Android開發者新瑞士軍刀Volley使用介紹

    Android開發者新瑞士軍刀Volley使用介紹

    相關軟件相關文章發表評論 來源:張興業時間:2013/10/10 10:09:36字體大?。?em class="fontsize">A-A+

    作者:張興業點擊:127次評論:0次標簽: Volley

    • 類型:文件處理大?。?i>209KB語言:中文 評分:7.0
    • 標簽:
    立即下載

    Volley是Android開發者新的瑞士軍刀,它提供了優美的框架,使得Android應用程序網絡訪問更容易和更快。Volley抽象實現了底層的HTTP Client庫,讓你不關注HTTP Client細節,專注于寫出更加漂亮、干凈的RESTful HTTP請求。另外,Volley請求會異步執行,不阻擋主線程。

    Volley提供的功能

    簡單的講,提供了如下主要的功能:

    1、封裝了的異步的RESTful 請求API;

    2、一個優雅和穩健的請求隊列;

    3、一個可擴展的架構,它使開發人員能夠實現自定義的請求和響應處理機制;

    4、能夠使用外部HTTP Client庫;

    5、緩存策略;

    6、自定義的網絡圖像加載視圖(NetworkImageView,ImageLoader等);

    為什么使用異步HTTP請求?

    Android中要求HTTP請求異步執行,如果在主線程執行HTTP請求,可能會拋出android.os.NetworkOnMainThreadException  異常。阻塞主線程有一些嚴重的后果,它阻礙UI渲染,用戶體驗不流暢,它可能會導致可怕的ANR(Application Not Responding)。要避免這些陷阱,作為一個開發者,應該始終確保HTTP請求是在一個不同的線程。

    怎樣使用Volley

    這篇博客將會詳細的介紹在應用程程中怎么使用volley,它將包括一下幾方面:

    1、安裝和使用Volley庫

    2、使用請求隊列

    3、異步的JSON、String請求

    4、取消請求

    5、重試失敗的請求,自定義請求超時

    6、設置請求頭(HTTP headers)

    7、使用Cookies

    8、錯誤處理

    安裝和使用Volley庫

    引入Volley非常簡單,首先,從git庫先克隆一個下來:

    git clone https://android.googlesource.com/platform/frameworks/volley

    然后編譯為jar包,再把jar包放到自己的工程的libs目錄。

    使用請求隊列

    Volley的所有請求都放在一個隊列,然后進行處理,這里是你如何將創建一個請求隊列:

    RequestQueue mRequestQueue = Volley.newRequestQueue(this); // 'this' is Context

    理想的情況是把請求隊列集中放到一個地方,最好是初始化應用程序類中初始化請求隊列,下面類做到了這一點:

    public class ApplicationController extends Application {
    
        /**
         * Log or request TAG
         */
        public static final String TAG = "VolleyPatterns";
    
        /**
         * Global request queue for Volley
         */
        private RequestQueue mRequestQueue;
    
        /**
         * A singleton instance of the application class for easy access in other places
         */
        private static ApplicationController sInstance;
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            // initialize the singleton
            sInstance = this;
        }
    
        /**
         * @return ApplicationController singleton instance
         */
        public static synchronized ApplicationController getInstance() {
            return sInstance;
        }
    
        /**
         * @return The Volley Request queue, the queue will be created if it is null
         */
        public RequestQueue getRequestQueue() {
            // lazy initialize the request queue, the queue instance will be
            // created when it is accessed for the first time
            if (mRequestQueue == null) {
                mRequestQueue = Volley.newRequestQueue(getApplicationContext());
            }
    
            return mRequestQueue;
        }
    
        /**
         * Adds the specified request to the global queue, if tag is specified
         * then it is used else Default TAG is used.
         * 
         * @param req
         * @param tag
         */
        public <T> void addToRequestQueue(Request<T> req, String tag) {
            // set the default tag if tag is empty
            req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    
            VolleyLog.d("Adding request to queue: %s", req.getUrl());
    
            getRequestQueue().add(req);
        }
    
        /**
         * Adds the specified request to the global queue using the Default TAG.
         * 
         * @param req
         * @param tag
         */
        public <T> void addToRequestQueue(Request<T> req) {
            // set the default tag if tag is empty
            req.setTag(TAG);
    
            getRequestQueue().add(req);
        }
    
        /**
         * Cancels all pending requests by the specified TAG, it is important
         * to specify a TAG so that the pending/ongoing requests can be cancelled.
         * 
         * @param tag
         */
        public void cancelPendingRequests(Object tag) {
            if (mRequestQueue != null) {
                mRequestQueue.cancelAll(tag);
            }
        }
    }

    異步的JSON、String請求

    Volley提供了以下的實用工具類進行異步HTTP請求:

    JsonObjectRequest — To send and receive JSON Object from the Server

    JsonArrayRequest — To receive JSON Array from the Server

    StringRequest — To retrieve response body as String (ideally if you intend to parse the response by yourself)

    JsonObjectRequest

    這個類可以用來發送和接收JSON對象。這個類的一個重載構造函數允許設置適當的請求方法(DELETE,GET,POST和PUT)。如果您正在使用一個RESTful服務端,可以使用這個類。下面的示例顯示如何使GET和POST請求。

    GET請求:

    final String URL = "/volley/resource/12";
    // pass second argument as "null" for GET requests
    JsonObjectRequest req = new JsonObjectRequest(URL, null,
           new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {
                   try {
                       VolleyLog.v("Response:%n %s", response.toString(4));
                   } catch (JSONException e) {
                       e.printStackTrace();
                   }
               }
           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   VolleyLog.e("Error: ", error.getMessage());
               }
           });
    
    // add the request object to the queue to be executed
    ApplicationController.getInstance().addToRequestQueue(req);
    

    POST請求:

    final String URL = "/volley/resource/12";
    // Post params to be sent to the server
    HashMap<String, String> params = new HashMap<String, String>();
    params.put("token", "AbCdEfGh123456");
    
    JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
           new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {
                   try {
                       VolleyLog.v("Response:%n %s", response.toString(4));
                   } catch (JSONException e) {
                       e.printStackTrace();
                   }
               }
           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   VolleyLog.e("Error: ", error.getMessage());
               }
           });
    
    // add the request object to the queue to be executed
    ApplicationController.getInstance().addToRequestQueue(req);

    JsonArrayRequest

    這個類可以用來接受 JSON Arrary,不支持JSON Object。這個類現在只支持 HTTP GET。由于支持GET,你可以在URL的后面加上請求參數。類的構造函數不支持請求參數。

    final String URL = "/volley/resource/all?count=20";
    JsonArrayRequest req = new JsonArrayRequest(URL, new Response.Listener<JSONArray> () {
        @Override
        public void onResponse(JSONArray response) {
            try {
                VolleyLog.v("Response:%n %s", response.toString(4));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    });
    
    // add the request object to the queue to be executed
    ApplicationController.getInstance().addToRequestQueue(req);

    StringRequest

    這個類可以用來從服務器獲取String,如果想自己解析請求響應可以使用這個類,例如返回xml數據。它還可以使用重載的構造函數定制請求。

    final String URL = "/volley/resource/recent.xml";
    StringRequest req = new StringRequest(URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            VolleyLog.v("Response:%n %s", response);
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.e("Error: ", error.getMessage());
        }
    });
    
    // add the request object to the queue to be executed
    ApplicationController.getInstance().addToRequestQueue(req);

    取消請求

    Volley提供了強大的API取消未處理或正在處理的請求。取消請求最簡單的方法是調用請求隊列cancelAll(tag)的方法,前提是你在添加請求時設置了標記。這樣就能使標簽標記的請求掛起。

    給請求設置標簽:

    request.setTag("My Tag");

    使用ApplicationController添加使用了標簽的請求到隊列中:

    ApplicationController.getInstance().addToRequestQueue(request, "My Tag");

    取消所有指定標記的請求:

    mRequestQueue.cancelAll("My Tag");

    重試失敗的請求,自定義請求超時

    Volley中沒有指定的方法來設置請求超時時間,可以設置RetryPolicy 來變通實現。DefaultRetryPolicy類有個initialTimeout參數,可以設置超時時間。要確保最大重試次數為1,以保證超時后不重新請求。

    Setting Request Timeout

    request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));

    設置請求頭(HTTP headers)        如果你想失敗后重新請求(因超時),您可以指定使用上面的代碼,增加重試次數。注意最后一個參數,它允許你指定一個退避乘數可以用來實現“指數退避”來從RESTful服務器請求數據。

    有時候需要給HTTP請求添加額外的頭信息,一個常用的例子是添加 “Authorization”到HTTP 請求的頭信息。Volley請求類提供了一個 getHeaers()的方法,重載這個方法可以自定義HTTP 的頭信息。

    添加頭信息:

    JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
               new Response.Listener<JSONObject>() {
                   @Override
                   public void onResponse(JSONObject response) {
                       // handle response
                   }
               }, new Response.ErrorListener() {
                   @Override
                   public void onErrorResponse(VolleyError error) {
                       // handle error                        
                   }
               }) {
    
           @Override
           public Map<String, String> getHeaders() throws AuthFailureError {
               HashMap<String, String> headers = new HashMap<String, String>();
               headers.put("CUSTOM_HEADER", "Yahoo");
               headers.put("ANOTHER_CUSTOM_HEADER", "Google");
               return headers;
           }
       };

    使用Cookies

    Volley中沒有直接的API來設置cookies,Volley的設計理念就是提供干凈、簡潔的API來實現RESTful HTTP請求,不提供設置cookies是合理的。

    下面是修改后的ApplicationController類,這個類修改了getRequestQueue()方法,包含了 設置cookie方法,這些修改還是有些粗糙。

    // http client instance
    private DefaultHttpClient mHttpClient;
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            // Create an instance of the Http client. 
            // We need this in order to access the cookie store
            mHttpClient = new DefaultHttpClient();
            // create the request queue
            mRequestQueue = Volley.newRequestQueue(this, new HttpClientStack(mHttpClient));
        }
        return mRequestQueue;
    }
    
    /**
     * Method to set a cookie
     */
    public void setCookie() {
        CookieStore cs = mHttpClient.getCookieStore();
        // create a cookie
        cs.addCookie(new BasicClientCookie2("cookie", "spooky"));
    }
    
    
    // add the cookie before adding the request to the queue
    setCookie();
    
    // add the request to the queue
    mRequestQueue.add(request);

    錯誤處理

    正如前面代碼看到的,在創建一個請求時,需要添加一個錯誤監聽onErrorResponse。如果請求發生異常,會返回一個VolleyError實例。

    以下是Volley的異常列表:

    AuthFailureError:如果在做一個HTTP的身份驗證,可能會發生這個錯誤。

    NetworkError:Socket關閉,服務器宕機,DNS錯誤都會產生這個錯誤。

    NoConnectionError:和NetworkError類似,這個是客戶端沒有網絡連接。

    ParseError:在使用JsonObjectRequest或JsonArrayRequest時,如果接收到的JSON是畸形,會產生異常。

    SERVERERROR:服務器的響應的一個錯誤,最有可能的4xx或5xx HTTP狀態代碼。

    TimeoutError:Socket超時,服務器太忙或網絡延遲會產生這個異常。默認情況下,Volley的超時時間為2.5秒。如果得到這個錯誤可以使用RetryPolicy。

    可以使用一個簡單的Help類根據這些異常提示相應的信息:

    public class VolleyErrorHelper {
         /**
         * Returns appropriate message which is to be displayed to the user 
         * against the specified error object.
         * 
         * @param error
         * @param context
         * @return
         */
      public static String getMessage(Object error, Context context) {
          if (error instanceof TimeoutError) {
              return context.getResources().getString(R.string.generic_server_down);
          }
          else if (isServerProblem(error)) {
              return handleServerError(error, context);
          }
          else if (isNetworkProblem(error)) {
              return context.getResources().getString(R.string.no_internet);
          }
          return context.getResources().getString(R.string.generic_error);
      }
      
      /**
      * Determines whether the error is related to network
      * @param error
      * @return
      */
      private static boolean isNetworkProblem(Object error) {
          return (error instanceof NetworkError) || (error instanceof NoConnectionError);
      }
      /**
      * Determines whether the error is related to server
      * @param error
      * @return
      */
      private static boolean isServerProblem(Object error) {
          return (error instanceof ServerError) || (error instanceof AuthFailureError);
      }
      /**
      * Handles the server error, tries to determine whether to show a stock message or to 
      * show a message retrieved from the server.
      * 
      * @param err
      * @param context
      * @return
      */
      private static String handleServerError(Object err, Context context) {
          VolleyError error = (VolleyError) err;
      
          NetworkResponse response = error.networkResponse;
      
          if (response != null) {
              switch (response.statusCode) {
                case 404:
                case 422:
                case 401:
                    try {
                        // server might return error like this { "error": "Some error occured" }
                        // Use "Gson" to parse the result
                        HashMap<String, String> result = new Gson().fromJson(new String(response.data),
                                new TypeToken<Map<String, String>>() {
                                }.getType());
    
                        if (result != null && result.containsKey("error")) {
                            return result.get("error");
                        }
    
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    // invalid request
                    return error.getMessage();
    
                default:
                    return context.getResources().getString(R.string.generic_server_down);
                }
          }
            return context.getResources().getString(R.string.generic_error);
      }
    }

    總結:

    Volley是一個非常好的庫,你可以嘗試使用一下,它會幫助你簡化網絡請求,帶來更多的益處。

    我也希望更加全面的介紹Volley,以后可能會介紹使用volley加載圖像的內容,歡迎關注。

    謝謝你的閱讀,希望你能喜歡。

      hosts修復軟件
      (60)hosts修復軟件
      文件是計算機中一個舉足輕重的文件,該文件有一個比較大的特點就是沒有擴展名。經常在一些電腦個性技巧以及其他領域方面會用到,西西提供文件修復工具軟件下載大全。官方介紹是一個沒有擴展名的系統文件,可以用記事本等工具打開,其作用就是將一些常用的網址域名與其對應的地址建立一個關聯數據庫,當用戶在瀏覽器中輸入一個需要登錄的網址時,系統會首先自動從文件中尋找對應的地址,一旦找到系統會立即打開對應網頁,如果沒有找...更多>>

      相關評論

      閱讀本文后您有什么感想? 已有人給出評價!

      • 8 喜歡喜歡
      • 3 頂
      • 1 難過難過
      • 5 囧
      • 3 圍觀圍觀
      • 2 無聊無聊

      熱門評論

      最新評論

      第 1 樓 湖北電信 網友 客人 發表于: 2013/11/4 15:12:23
      使用Method.Post請求時,你做過測試嗎?

      支持( 0 ) 蓋樓(回復)

      發表評論 查看所有評論(0)

      昵稱:
      表情: 高興 可 汗 我不要 害羞 好 下下下 送花 屎 親親
      字數: 0/500 (您的評論需要經過審核才能顯示)
      女人让男人桶30分钟免费视频,女人张开腿让男人桶个爽,一进一出又大又粗爽视频
    • <td id="ae6ms"><li id="ae6ms"></li></td>
    • <xmp id="ae6ms"><td id="ae6ms"></td><table id="ae6ms"></table>
    • <table id="ae6ms"></table>
    • <td id="ae6ms"></td>
      <td id="ae6ms"></td>
    • <table id="ae6ms"></table><table id="ae6ms"><td id="ae6ms"></td></table>
    • <td id="ae6ms"></td>
    • <table id="ae6ms"><li id="ae6ms"></li></table>
    • <table id="ae6ms"></table>