Volley提供了优美的框架,使得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目录。
import info.androidhive.volleyexamples.volley.utils.LruBitmapCache; import android.app.Application; import android.text.TextUtils; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; public class AppController extends Application { public static final String TAG = AppController.class .getSimpleName(); private RequestQueue mRequestQueue; private ImageLoader mImageLoader; private static AppController mInstance; @Override public void onCreate() { super.onCreate(); mInstance = this; } public static synchronized AppController getInstance() { return mInstance; } public RequestQueue getRequestQueue() { if (mRequestQueue == null) { mRequestQueue = Volley.newRequestQueue(getApplicationContext()); } return mRequestQueue; } public ImageLoader getImageLoader() { getRequestQueue(); if (mImageLoader == null) { mImageLoader = new ImageLoader(this.mRequestQueue, new LruBitmapCache()); } return this.mImageLoader; } public <T> void addToRequestQueue(Request<T> req, String tag) { // set the default tag if tag is empty req.setTag(TextUtils.isEmpty(tag) ? TAG : tag); getRequestQueue().add(req); } public <T> void addToRequestQueue(Request<T> req) { req.setTag(TAG); getRequestQueue().add(req); } public void cancelPendingRequests(Object tag) { if (mRequestQueue != null) { mRequestQueue.cancelAll(tag); } } }
1、Making json object request
String url = ""; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); // hide the progress dialog pDialog.hide(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
2、Making json array request
// Tag used to cancel the request String tag_json_arry = "json_array_req"; String url = "http://api.androidhive.info/volley/person_array.json"; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonArrayRequest req = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(req, tag_json_arry);
3、Making String request
// Tag used to cancel the request String tag_string_req = "string_req"; String url = "http://api.androidhive.info/volley/string_response.html"; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); StringRequest strReq = new StringRequest(Method.GET, url, new Response.Listener<String>() { @Override public void onResponse(String response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }); // Adding request to request queue AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
4、Adding post parameters
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "http://api.androidhive.info/volley/person_object.json"; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }) { @Override protected Map<String, String> getParams() { Map<String, String> params = new HashMap<String, String>(); params.put("name", "Androidhive"); params.put("email", "abc@androidhive.info"); params.put("password", "password123"); return params; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
5、Adding request headers
// Tag used to cancel the request String tag_json_obj = "json_obj_req"; String url = "http://api.androidhive.info/volley/person_object.json"; ProgressDialog pDialog = new ProgressDialog(this); pDialog.setMessage("Loading..."); pDialog.show(); JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST, url, null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { Log.d(TAG, response.toString()); pDialog.hide(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { VolleyLog.d(TAG, "Error: " + error.getMessage()); pDialog.hide(); } }) { /** * Passing some request headers * */ @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/json"); headers.put("apiKey", "xxxxxxxxxxxxxxx"); return headers; } }; // Adding request to request queue AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
Android working with Volley Library,布布扣,bubuko.com
Android working with Volley Library
原文:http://www.cnblogs.com/lyp3314/p/3815769.html