Android Volley 框架的使用

为什么使用Volley 框架
  1. 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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值