天天看點

Android Volley的基本用法--StringRequest以及JsonReques

1. Volley簡介

volley是android新的網絡通信架構,既可以非常簡單地進行HTTP通信,也可以輕松加載網絡上的圖檔。除了簡單易用之外,Volley在性能方面也進行了大幅度的調整,它的設計目标就是非常适合去進行資料量不大,但通信頻繁的網絡操作,而對于大資料量的網絡操作,比如說下載下傳檔案等,Volley的表現就會非常差!

2. 下載下傳Volley

下載下傳連結: 連結:http://pan.baidu.com/s/1eQfJA1O 密碼:396r

建立一個Android項目,将volley.jar檔案複制到libs目錄下!

3. StringRequest的用法

我們就從最基本的HTTP通信開始學習吧,即發起一條HTTP請求,然後接收HTTP響應。首先需要擷取到一個RequestQueue對象,可以調用如下方法擷取到:

RequestQueue mQueue = Volley.newRequestQueue(context);

發送HTTP請求,建立StringRequest 對象,請求方法有兩種:GET和POST

   StringRequest sq = newStringRequest(method, url, listener, errorListener)

   第一個參數是HTTP請求方式,第二個參數就是目标伺服器的URL位址,第三個參數是伺服器響應成功的回調,第四個參數是伺服器響應失敗的回調

   第一個參數不寫,預設就是使用GET方法

   對于POST方法,StringRequest沒有提供設定POST參數的方法,但是當發出POST請求的時候,Volley會嘗試調用StringRequest的父類——Request中的getParams()方法來擷取POST參數,隻需要在StringRequest的匿名類中重寫getParams()方法,在這裡設定POST參數就可以了。

StringRequest stringRequest = new StringRequest(Method.POST, url,  listener, errorListener) {
	@Override
	protected Map<String, String> getParams() throws AuthFailureError {
		Map<String, String> map = new HashMap<String, String>();
		map.put("params1", "value1");
		map.put("params2", "value2");
		return map;
	}
};
           

最後,将這個StringRequest對象添加到RequestQueue

mQueue.add(stringRequest);
           

4. JsonReques的用法

JsonReques是一個抽象類,要執行個體它的子類,JsonObjectRequest和JsonArrayRequest。用法跟StringRequest類似:

         JsonObjectRequestr = new JsonObjectRequest(method, url, jsonRequest, listener, errorListener)

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest("http://m.weather.com.cn/data/101010100.html", null,
		new Response.Listener<JSONObject>() {
			@Override
			public void onResponse(JSONObject response) {
				Log.d("TAG", response.toString());
			}
		}, new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Log.e("TAG", error.getMessage(), error);
			}
		});
           

響應的資料就是以JSON格式傳回

最後,将這個JsonReques對象添加到RequestQueue

mQueue.add(<span style="font-family: Arial;">jsonObjectRequest</span>);
           

這兩種方法都差不多!