介紹
谷歌開源的,
專注于處理高頻率的數(shù)據(jù)比較小的請求
內部仍然是使用的HttpURLConnection和HttpClient進行網絡請求的,
只是對于不同的
Android版本進行了響應的切換这弧,
2.3之前使用的HttpClient垄懂,
2.3之后使用的是 HttpURLConnection
支持取消請求
具有網絡請求和圖片加載的功能
添加依賴
compile 'com.android.volley:volley:1.0.0'
創(chuàng)建RequestQueue請求隊列,它是用來執(zhí)行請求對象的
RequestQueue queue = Volley.newRequestQueue(this);
創(chuàng)建請求對象拟赊,這里使用最簡單的StringRequest:
StringRequest stringRequest = new StringRequest(Api.TEST, new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
text.setText(response);
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
執(zhí)行請求刺桃,將Request對象添加到RequestQueue中,即可
//3.執(zhí)行請求
queue.add(stringRequest);
使用JsonRequest進行請求吸祟,返回的是json對象
//1.創(chuàng)建JsonRequest請求
JsonObjectRequest joRequest = new JsonObjectRequest(url, null, new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
tv_result.setText(response.toString());
}
}, new MyErrorListener());
//2.執(zhí)行請求
queue.add(joRequest);
使用Volley發(fā)送post請求虏肾,需要自己重寫Request的getParams方法
public class PostReuqest extends StringRequest {
private Map<String, String> params;
public PostReuqest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(url, listener, errorListener);
}
public PostReuqest(int method,String url, Response.Listener<String> listener, Response.ErrorListener errorListener) {
super(method,url, listener, errorListener);
}
public void setParams(Map<String, String> params){
this.params = params;
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return params;
}
}
PostReuqest stringRequest = new PostReuqest(Request.Method.POST,Api.LOGIN, new com.android.volley.Response.Listener<String>() {
@Override
public void onResponse(String response) {
text.setText(response);
}
}, new com.android.volley.Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
HashMap<String,String> map = new HashMap<>();
map.put("username","hehehe");
map.put("password","12321");
stringRequest.setParams(map);