为什么使用Volley 框架
Android 开发经常涉及网络操作,虽然Android Sdk 提供 HttpClient 和 HttpUrlConnection 方式,当应用需要处理大量的数据,使用起来不方便。Volley 框架应运而生,下面列出Volley 框架几大优势:
① Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.②Volley provides transparent disk and memory caching.
③Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel.
④Volley provides powerful customization abilities.
⑤Volley provides Debugging and tracing tools
怎么用Volley 框架
1.Android Studio 直接在 build.gradle 文件加入以下代码并重新 Make Project,快捷键为Ctrl + F9
compile 'com.mcxiaoke.volley:library:1.0.19'
2.或者在GitHub直接下载:https://github.com/mcxiaoke/android-volley
3.下面开始真正使用 volley 框架啦,分为三小步:先创建RequestQueue队列,接着发出StringRequest请求消息,最后将请求消息添加进请求队列即可。顺便说明这样做好处:RequestQueue队列在一个 Activity 中只需要声明一次,它会缓存 Http请求,节省更多资源。
①创建 RequestQueue队列
//context表示上下文环境
RequestQueue requestQueue = Volley.newRequestQueue(context);
②发出HTTP请求消息
final String url = "http://www.163.com";//url以实际需要为准,最好定义为常量
new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d("TAG", response);
/**
* 由于volley使用ISO-8859-1编码,请求下来的中文数据会出现乱码
* 可以将 response 先转换编码格式
*/
String result = null;
try {
result = new String(response.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("TAG", error.getMessage(), error);
}
});
③开启 Http 请求
requestQueue.add(request);