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. 关于CSS重要知识点(1)

    1. 盒子模型 CSS处理网页内容时,会把每一个元素"放在"一个盒子里,也就是所谓的盒子模型. 盒子模型包括4部分:内容,内边距(padding),边框(border)和外边距(m ...

  2. http常见状态码有哪些?

    ajax常见面试题 1:什么是ajax?ajax作用是什么? 异步的javascript和xml AJAX 是一种用于创建快速动态网页的技术. ajax用来与后台交互 2:原生js ajax请求有几个 ...

  3. Android 原生 MediaPlayer 和 MediaCodec 的区别和联系(二)

    目录: (3)Android 官方网站 对 MediaPlayer的介绍 正文:  Android 官方网站 对 MediaPlayer的介绍         MediaPlayer      pub ...

  4. linux 权限管理命令chmod、文件和目录的权限的意义

    chmod /bin/chmod chmod [{ugoa}{+-=}{rwx}] [文件或目录]chmod [mode=421] [文件或目录]-R 递归修改 只有 root 和 所有者 可以修改一 ...

  5. spring shiro 集成

    1.向spring项目中添加shiro相关的依赖 <dependency> <groupId>commons-logging</groupId> <artif ...

  6. node(2)

    //app.js var express = require("express"); //以后的时后处理POST DELETE PATCH CHECKOUT 这些请求都可以用for ...

  7. Centos 使用C++11 编译

    今天编译代码,发现使用auto后无法编译,我的当前linux内核版本:(4.7之后即可支持C++11) 这时,在编译末尾加入 -std=c++11 就可以正常编译了.如:

  8. ExpressRoute 线路和路由域

    你必须订购一条 ExpressRoute 线路 ,以通过连接提供商将你的本地基础结构连接到 Azure.下图提供了你的 WAN 与 Azure 之间的连接的逻辑表示形式. ExpressRoute 线 ...

  9. Oracle EBS 应收发票取值

    SELECT ct.trx_number ,ctl.description ,fnd_flex_ext.get_segs('SQLGL' ,'GL#' ,gcc.chart_of_accounts_i ...

  10. Jquery 保留N位小数,且千位以上用","号隔开

    s:数据Value n:保留小数位数 function jinEFmoney(s, n) { if (s == '' || s == null) return '0.00'; n = n > 0 ...