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目录。

Creating Volley Singleton class

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的更多相关文章

  1. Android Studio导入System Library步骤

    转载请注明出处:http://www.cnblogs.com/cnwutianhao/p/6242170.html 请尊重知识产权!!!  同步更新到CSDN:http://blog.csdn.net ...

  2. [Android] 建立与使用Library

    [Android] 建立与使用Library 前言 使用Eclipse开发Android项目时,开发人员可以将可重用的程序代码,封装为Library来提供其他开发人员使用.本篇文章介绍如何将可重用的程 ...

  3. Android网络框架Volley(体验篇)

    Volley是Google I/O 2013推出的网络通信库,在volley推出之前我们一般会选择比较成熟的第三方网络通信库,如: android-async-http retrofit okhttp ...

  4. Android网络框架Volley(实战篇)

      之前讲了ym—— Android网络框架Volley(体验篇),大家应该了解了volley的使用,接下来我们要看看如何把volley使用到实战项目里面,我们先考虑下一些问题: 从上一篇来看 mQu ...

  5. Android框架之Volley与Glide

    PS:在看到这个题目的同时,你们估计会想,Volley与Glide怎么拿来一块说呢,他们虽然不是一个框架,但有着相同功能,那就是图片处理方面.首先我们先来看一下什么volley,又什么是glide. ...

  6. Android Library和Android APP、Java Library的区别

    Android Library和Android APP.Java Library的区别 Android Library在目录结构上与Android App相同,它能包含构建APP所需的一切(如源代码. ...

  7. Android网络框架-Volley实践 使用Volley打造自己定义ListView

    这篇文章翻译自Ravi Tamada博客中的Android Custom ListView with Image and Text using Volley 终于效果 这个ListView呈现了一些影 ...

  8. Android网络框架Volley

    Volley是Google I/O 2013推出的网络通信库,在volley推出之前我们一般会选择比较成熟的第三方网络通信库,如: android-async-http retrofit okhttp ...

  9. ym—— Android网络框架Volley(终极篇)

    转载请注明本文出自Cym的博客(http://blog.csdn.net/cym492224103).谢谢支持! 没看使用过Volley的同学能够,先看看Android网络框架Volley(体验篇)和 ...

随机推荐

  1. Chrome浏览器取消INPUT自动记忆下拉框

    项目中有一个搜索框,每次聚焦就会出现如下图自动记忆框,遮挡了项目的搜索列表 差了很多资料想要去掉它,最后发现在input上加上autocomplete="off"就可以了!

  2. React-Native开发之原生模块封装(Android)升级版

     本文主题:如何实现原生代码的复用,即如何将原生模块封装. (尊重劳动成果,转载请注明出处:http://blog.csdn.net/qq_25827845/article/details/52862 ...

  3. git push 提示 Everything up-to-date

    第一次在 Google Code 上弄项目,注册完毕后,尝试增加一个新文件用以测试 Git 是否好好工作.结果在 Push 时却显示 Every up-to-date,检查文件时却发现实际上一个都没更 ...

  4. ShortcutBadger添加桌面角标(Badge)

    1.简介:角标原本是苹果的ios中的东西,android原生并不支持角标,因为google的意思是让大家用notification(提示栏)即可,不过无妨,厉害的android第三方厂商可以通过在自定 ...

  5. java 内存分析之static

    源码: 内存分析: 源码: 静态方法:   用static 声明的方法为静态方法,在调用该方法时,不会将对象的引用传递给它,所以在static 方法中不可访问非static 的成员.   可以通过对象 ...

  6. html + css + jquery实现简单的进度条实例

    <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head><meta ...

  7. ORACLE RAC节点意外重启Node Eviction诊断流程图(11.2+)

  8. 常用CSS技术收藏

    常用CSS技术收藏 必须要掌握的技术 盒子模型 定位模型 定位模型 css sprite(雪碧/css精灵)相关 css sprite 坐标定位为何为负以及定位方法 布局 圣杯布局小结 规范 BEM ...

  9. POST请求上传多张图片并携带参数

    POST请求上传多张图片并携带参数 在iOS中,用POST请求携带参数上传图片是非常恶心的事情,HTTPBody部分完全需要我们自己来配置,这个HTTPBody分为3个部分,头部分可以携带参数,中间部 ...

  10. 17级-车辆工程-周金霖 计算机作业 MP4音乐网站