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. freecodecamp 基础算法题笔记

    数组与字符串的转化 字符串转化成数组 reverse方法翻转数组顺序 数组转化成字符串. function reverseString(str) { a= str.split("" ...

  2. ios虚拟机安装(一)

    安装软件:vmwarestation-v9.0.1()   MAC OS X Mountain Lion 10.8.2 xcode 4.6.2 一定要安装补丁:unlock-all-v110(mac系 ...

  3. zabbix使用问题

    1中文乱码 https://www.linuxidc.com/Linux/2017-08/146162.htm 软件 说明 备注 zabbix 3.4.7 操作系统 Centos7 问题描述:图表内容 ...

  4. leetCode题解之寻找一个数在有序数组中的范围Search for a Range

    1.问题描述 Given an array of integers sorted in ascending order, find the starting and ending position o ...

  5. maven问题总结

    1.maven下载jar包速度慢 1.maven下载jar包速度慢(解决办法) 现在maven项目非常流行,因为它对jar实行了一个非常方便的管理,我们可以通过在pom.xml文件中做对应的配置即可将 ...

  6. SPA SEO thought

    angular, vue,ember,backbone等javascript framework大大方便了现代web开发,带来了用户体验的巨大提高,但是同时带来了另一个问题:SEO,由于搜索引擎无法运 ...

  7. Tomcat性能监控之Probe

    目前采用java进行开发的系统居多,这些系统运行在java容器中,通过对容器的监控可以了解到java进程的运行状况,分析java程序问题.目前市面上流行的中间件有很多(Tomcat.jetty.jbo ...

  8. HTML--<frameset>標簽

    <html><frameset rows="20,80"> <frame src="/example/html/frame_a.html&q ...

  9. 小鸡G4工程款 上手体验

    前言:之前只是抱着试一试的态度在小鸡活动贴下报名,说实话之前并没有抱希望能够没选中.所以非常感谢小鸡团队给我的这次机会.这应该是我第一次参与厂家的内测活动.希望能给小鸡团队,给广大玩家带来一片实用的上 ...

  10. Redis学习---Redis操作之String

    set(name, value, ex=None, px=None, nx=False, xx=False) 在Redis中设置值,默认,不存在则创建,存在则修改 参数:      ex,过期时间(秒 ...