Android Volley使用
Get和Post區別
- GET用來從服務端獲取數據,POST用于上傳或者修改數據
- GET大小限制在2KB以內,POST一般沒有限制
- GET參數在URL,POST參數在請求主體中(也就是用send發送),安全性POST高
- 部分瀏覽器會緩存GET請求的response,以至于相同的GET請求會得到相同的response即使服務端的數據已經改變,POST不會被緩存
- 使用XMLHttpRequest時,POST需要顯式指定請求頭
下載Volley的jar包
git clone https://android.googlesource.com/platform/frameworks/volley
使用方法
- 創建一個RequestQueen對象
- 創建一個StringRequest對象
- 將StringRequest對象加入RequestQueen中
`StringRequest stringRequest = new StringRequest (Method.POST, url, listener, errorListener)
{
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;
}
};`
JSONRequest
jsonRequest是一個抽象類,無法創建實例,JsonRequest有兩個子類,
JsonObjectRequest和JsonArrayRequest,一個是請求一段JSON數據的,一個是用于請求一段JSON數組的
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);
}
}); `JsonObjectRequest對象添加到RequestQueue里
mQueue.add(jsonObjectRequest);
這里我們填寫的URL地址是http://m.weather.com.cn/data/101010100.html,這是中國天氣網提供的一個查詢天氣信息的接口,響應的數據就是以JSON格式返回的,然后我們在onResponse()方法中將返回的數據打印出來。