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. sqlserver年月日转汉字大写--自定义函数--繁体

    两个自定义函数结合 函数一: create function convertNumToChinese ()) ) as begin ) ' set @temStr = '壹' ' set @temSt ...

  2. dojox.grid.DataGrid显示数据的方法(转)

    第一种:数据存在本地或者已经写死的JSON对象中,不需要跟服务端进行数据传输 <%@ page language="java" contentType="text/ ...

  3. 云数据库Redis版256M双机热备款

    云数据库Redis版是兼容Redis协议标准的.提供持久化的缓存式数据库服务,基于高可靠双机热备架构:全新推出的256M小规格款,适用于高QPS.小数据量业务,并支持免费全量迁移,完美服务于个人开发者 ...

  4. Pwn Heap With Tcache

    Pwn Heap With Tcache 前言 glibc 2.26 开始引入了 tcache , 相关的 commit 可以看 这里 .加入 tcache 对性能有比较大的提升,不过由于 tcach ...

  5. 【转】虚拟机安装Ubuntu的上网设置(有线网络和无线网络)

    虚拟机下ubuntu共享方式上网: 一. 有线网络 在有线网络的条件下,vmware的安装非常简单,上网方式几乎不用怎么设置(默认NAT模式)    如果默认情况下不能上网,则按以下步骤尝试: *** ...

  6. libgdx自问自答

    1.使用gdx-steup.jar生成的desktop项目导入idea运行报如下错误,如何解决? 答:原因是assets目录默认是普通目录,idea编译项目时不会把普通目录下的内容输出到classpa ...

  7. npm install时报错“Unexpected end of JSON input while parsing near...”解决方法

    执行:npm cache clean --force 即可解决此问题

  8. lambda 表达式的由来

    相关技术点:函数指针.C#委托.匿名方法.lambda表达式 谈到lambda表达式,首先从委托讲起, 委托是持有一个或者多个方法的对象,这个特性有点像C中的函数指针,可以指向不同的方法,下面的例子是 ...

  9. Python学习---爬虫学习[requests模块]180411

    模块安装 安装requests模块 pip3 install requests 安装beautifulsoup4模块 [更多参考]https://blog.csdn.net/sunhuaqiang1/ ...

  10. Linux系统设置运行级别

    设置运行级别 查看开机加载级别:7个级别 规范场景默认都是3         cat /etc/inittab --> 系统开机启动加载的文件,可以设置运行级别 # Default runlev ...