Android异步HTTP请求框架Volley的使用

原文地址:http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/#

Volley是Android 开发者的一把“瑞士军刀”,它提供了一些好的工具让在Android 开发中使用网络请求更快,更便捷。Volley的优点在于它封装了HTTP请求的底层实现,让开发者更加专注地写出优雅干净的RESTful风格的HTTP请求。同时,Volley中所有的请求都是在另外的线程中执行,不会阻塞主线程。

Volley的特性

Volley的重要特性:

  • 高水平的异步RESTful风格的HTTP请求的接口
  • 健壮、优雅的请求队列
  • 扩展性强,允许开发者实现自定义的请求和响应处理机制
  • 可以使用扩展的HTTP库
  • 健壮的缓存策略
  • 加载和缓存网络图片的自定义View如(etworkImageView, ImageLoader etc)

为什么要使用异步的HTTP请求

在Android开发过程中,使用异步的HTTP请求是一个很好的惯例,事实上,从HoneyComb 版本开始,这不仅仅只是一个惯例,而是你必须在主线程中实现异步的HTTP请求,否则,抛出android.os.NetworkOnMainThreadException的异常。阻塞主线程会导致严重的后果,妨碍UI呈现,影响用户的流畅的用户体验,更严重的会导致ANR(应用无响应)。为了避免这些陷阱,作为Android开发者,必须保证HTTP请求不在主线程中执行。

如何使用Volley

我将在博客中讨论下面这些内容,在本文结束后,你将对Volley有一个清晰的了解,并且知道如何在应用中使用它。

  • 使用Volley作为项目的库
  • 使用Request Queue
  • 使用异步的String和JSON HTTP请求
  • 取消请求
  • 重试失败的请求,定制请求超时
  • 设置请求的头部(HTTP 头部)
  • 使用缓存
  • 错误处理

获取Volley并作为库使用

Volley是Android开放源代码项目(AOSP)的一部分而不是一个jar文件,因此,在项目中引入Volley最简单的方式是把Volley克隆下来,并把它设置为当前项目依赖的库。

作为库使用
用Git使用下面的的命令把Volley的代码库克隆下来,并把它作为Android library project导入到项目中。

git clone https://android.googlesource.com/platform/frameworks/volley

作为jar使用
先用Git把Volley克隆下来,然后使用下面的命令导出jar文件,最后把导出的jar文件放入到项目根目录下面的libs文件夹中。

# in Volley project root (ensure the `android` executable is in your path)
$ android update project -p .
# the following command will create a JAR file and put it in ./bin
$ ant jar

使用请求队列

Volley中所有的请求都是先添加到一个队列里面,然后再处理,下面的代码用来创建一个请求队列:

RequestQueue mRequestQueue = Volley.newRequestQueue(this); // 'this' is Context

理想情况下,应该把请求队列放到一个集中的地方,最适合初始化队列的地方是Application类,下面将展示如何使用:

public class ApplicationController extends Application {

    /**
     * Log or request TAG
     */
    public static final String TAG = "VolleyPatterns";

    /**
     * Global request queue for Volley
     */
    private RequestQueue mRequestQueue;

    /**
     * A singleton instance of the application class for easy access in other places
     */
    private static ApplicationController sInstance;

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize the singleton
        sInstance = this;
    }

    /**
     * @return ApplicationController singleton instance
     */
    public static synchronized ApplicationController getInstance() {
        return sInstance;
    }

    /**
     * @return The Volley Request queue, the queue will be created if it is null
     */
    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mRequestQueue;
    }

    /**
     * Adds the specified request to the global queue, if tag is specified
     * then it is used else Default TAG is used.
     * 
     * @param req
     * @param tag
     */
    public <T> void addToRequestQueue(Request<T> req, String tag) {
        // set the default tag if tag is empty
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        VolleyLog.d("Adding request to queue: %s", req.getUrl());

        getRequestQueue().add(req);
    }

    /**
     * Adds the specified request to the global queue using the Default TAG.
     * 
     * @param req
     * @param tag
     */
    public <T> void addToRequestQueue(Request<T> req) {
        // set the default tag if tag is empty
        req.setTag(TAG);

        getRequestQueue().add(req);
    }

    /**
     * Cancels all pending requests by the specified TAG, it is important
     * to specify a TAG so that the pending/ongoing requests can be cancelled.
     * 
     * @param tag
     */
    public void cancelPendingRequests(Object tag) {
        if (mRequestQueue != null) {
            mRequestQueue.cancelAll(tag);
        }
    }
}

使用异步HTTP请求

Volley提供了下面这些类来实现异步的HTTP请求:

  • JsonObjectRequest — 发送和接收 JSONObject格式的数据
  • JsonArrayRequest — 发送和接收 JSONArray格式的数据
  • StringRequest — 发送和接收 String格式的数据

注意:如果需要发送带参数的请求,需要覆盖请求类的getParams()或getBody()方法。

JsonObjectRequest
这个类可以用来发送和接收JSON对象。这个类的重载的构造函数允许设置适当的请求方法(DELETE、GET、POST和PUT)。这是类适用于Android应用经常和一个基于rest的后端交互的场景。下面的例子展示如何使GET和POST请求。

使用 HTTP GET 方法:

final String URL = "/volley/resource/12";
// pass second argument as "null" for GET requests
JsonObjectRequest req = new JsonObjectRequest(URL, null,
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

使用 HTTP GET 方法:

final String URL = "/volley/resource/12";
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("token", "AbCdEfGh123456");

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
       new Response.Listener<JSONObject>() {
           @Override
           public void onResponse(JSONObject response) {
               try {
                   VolleyLog.v("Response:%n %s", response.toString(4));
               } catch (JSONException e) {
                   e.printStackTrace();
               }
           }
       }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               VolleyLog.e("Error: ", error.getMessage());
           }
       });

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

JsonArrayRequest

这个类可以用来检索JSON数组而不是JSON对象,目前只支持HTTP GET。可以添加一些属性参数,附加在URL后面。构造函数不接受请求参数。

final String URL = "/volley/resource/all?count=20";
JsonArrayRequest req = new JsonArrayRequest(URL, new Response.Listener<JSONArray> () {
    @Override
    public void onResponse(JSONArray response) {
        try {
            VolleyLog.v("Response:%n %s", response.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
    }
});

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

StringRequest

这个类可以用来从服务器获取响应字符串,理想情况下时,可以使用这个类解析任意格式的response ,例如,是XML格式。它还提供了重载的构造函数,从而可以进一步定制HTTP请求。

final String URL = "/volley/resource/recent.xml";
StringRequest req = new StringRequest(URL, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        VolleyLog.v("Response:%n %s", response);
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.e("Error: ", error.getMessage());
    }
});

// add the request object to the queue to be executed
ApplicationController.getInstance().addToRequestQueue(req);

有时可能需要设置请求的优先级,比如提高某些请求的优先级。Volley会先处理优先级较高的请求,在优先级相同的情况下,按先进先出的顺序处理。设置优先级需要覆盖请求类的getPriority()方法。当前可用的优先级——Priority.LOW Priority.NORMAL,Priority.HIGH Priority.IMMEDIATE。

取消请求

Volley提供强大的api来完成取消未处理或正在处理的请求,如果用户旋转设备,Activity将重新启动,这时需要取消真正进行的HTTP请求。取消请求最简单的方法是调用请求队列的cancelAll(TAG)方法,前提是在添加请求到请求队列之前,先设置TAG。Volley可以在一个方法里面取消所有带某个TAG的HTTP请求。
为请求设置TAG:

request.setTag("My Tag");

利用上面的ApplicationController类,将请求添加到请求队列:

ApplicationController.getInstance().addToRequestQueue(request, "My Tag");

取消所有指定标签的请求:

mRequestQueue.cancelAll("My Tag");

利用上面的ApplicationController类,取消请求:

ApplicationController.getInstance().cancelPendingRequests("My Tag");

重试失败的请求和定制请求超时

在Voley没有直接的方法来指定请求超时时间值,但是有一个解决方案,您需要设置一个RetryPolicy请求对象。DefaultRetryPolicy类一个叫做initialTimeout参数,这可以用于指定请求超时的时间,确保最大重试计数为1,这样可以让Volley不重试超时的请求。

request.setRetryPolicy(new DefaultRetryPolicy(20 * 1000, 1, 1.0f));

如果你想重试失败的请求(由于超时),你可以修改上面的代码,增加重试计数。注意最后一个参数,它允许您指定一个倒扣的乘数效应,可用于实现“exponential backoff”,适用一些基于rest的服务。

设置请求的头文件(HTTP headers)

有时有必要添加额外的HTTP请求头,一种常见的情况是添加一个“授权”请求头用来实现HTTP基本身份验证。Volley请求类提供了getHeaders()方法,自定义HTTP请求头时需要重写这个方法。

添加定制的头文件:

JsonObjectRequest req = new JsonObjectRequest(URL, new JSONObject(params),
           new Response.Listener<JSONObject>() {
               @Override
               public void onResponse(JSONObject response) {
                   // handle response
               }
           }, new Response.ErrorListener() {
               @Override
               public void onErrorResponse(VolleyError error) {
                   // handle error                        
               }
           }) {

       @Override
       public Map<String, String> getHeaders() throws AuthFailureError {
           HashMap<String, String> headers = new HashMap<String, String>();
           headers.put("CUSTOM_HEADER", "Yahoo");
           headers.put("ANOTHER_CUSTOM_HEADER", "Google");
           return headers;
       }
   };

使用 cookies

Volley没有直接的API来设置cookie。这是有道理的,因为Volley的核心理念是提供干净的API来编写RESTful HTTP请求,大部分的RESTful API提供者喜欢身份验证令牌,而不是cookie。Volley使用cookie过程比较复杂,不是很直接。
这里的修改ApplicationController类中的getRequestQueue ,设置cookie:

// http client instance
private DefaultHttpClient mHttpClient;
public RequestQueue getRequestQueue() {
    // lazy initialize the request queue, the queue instance will be
    // created when it is accessed for the first time
    if (mRequestQueue == null) {
        // Create an instance of the Http client. 
        // We need this in order to access the cookie store
        mHttpClient = new DefaultHttpClient();
        // create the request queue
        mRequestQueue = Volley.newRequestQueue(this, new HttpClientStack(mHttpClient));
    }
    return mRequestQueue;
}

/**
 * Method to set a cookie
 */
public void setCookie() {
    CookieStore cs = mHttpClient.getCookieStore();
    // create a cookie
    cs.addCookie(new BasicClientCookie2("cookie", "spooky"));
}


// add the cookie before adding the request to the queue
setCookie();

// add the request to the queue
mRequestQueue.add(request);

错误处理

在上面的代码示例创建一个请求对象,Volley需要指定一个错误监听器,Volley执行请求时出现错误时,调用onErrorResponse回调方法的监听器,传递VolleyError对象的一个实例。

下面是Volley的异常列表:

  • AuthFailureError —如果你想做Http基本身份验证,这个错误是最有可能的。
  • NetworkError — Socket断开,服务器不能访问,DNS问题,可能导致这个错误。
  • NoConnectionError — 与NetworkError相似,当设备没有互联网连接,应用的错误处理逻辑可以将clubNetworkError与NoConnectionError放在一起,同样的处理。
  • ParseError — 在使用JsonObjectRequest或者JsonArrayRequest时,如果收到将的JSON格式是错误的,那么出现这个异常。
  • ServerError — 服务器回复了一个错误,很可能与4 xx或5 xx HTTP状态代码。
  • TimeoutError —Socket超时,服务器太忙,来不及处理请求或网络延迟问题。默认Volley超时请求时间是2.5秒,使用一个RetryPolicy如果一直出现这个错误。

当异常发生时,可以使用一个简单的VolleyErrorHelper类来显示错误消息:

public class VolleyErrorHelper {
     /**
     * Returns appropriate message which is to be displayed to the user 
     * against the specified error object.
     * 
     * @param error
     * @param context
     * @return
     */
  public static String getMessage(Object error, Context context) {
      if (error instanceof TimeoutError) {
          return context.getResources().getString(R.string.generic_server_down);
      }
      else if (isServerProblem(error)) {
          return handleServerError(error, context);
      }
      else if (isNetworkProblem(error)) {
          return context.getResources().getString(R.string.no_internet);
      }
      return context.getResources().getString(R.string.generic_error);
  }

  /**
  * Determines whether the error is related to network
  * @param error
  * @return
  */
  private static boolean isNetworkProblem(Object error) {
      return (error instanceof NetworkError) || (error instanceof NoConnectionError);
  }
  /**
  * Determines whether the error is related to server
  * @param error
  * @return
  */
  private static boolean isServerProblem(Object error) {
      return (error instanceof ServerError) || (error instanceof AuthFailureError);
  }
  /**
  * Handles the server error, tries to determine whether to show a stock message or to 
  * show a message retrieved from the server.
  * 
  * @param err
  * @param context
  * @return
  */
  private static String handleServerError(Object err, Context context) {
      VolleyError error = (VolleyError) err;

      NetworkResponse response = error.networkResponse;

      if (response != null) {
          switch (response.statusCode) {
            case 404:
            case 422:
            case 401:
                try {
                    // server might return error like this { "error": "Some error occured" }
                    // Use "Gson" to parse the result
                    HashMap<String, String> result = new Gson().fromJson(new String(response.data),
                            new TypeToken<Map<String, String>>() {
                            }.getType());

                    if (result != null && result.containsKey("error")) {
                        return result.get("error");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                // invalid request
                return error.getMessage();

            default:
                return context.getResources().getString(R.string.generic_server_down);
            }
      }
        return context.getResources().getString(R.string.generic_error);
  }
}

总结

Volley确实是一个不错的库,你应该认真考虑去尝试。它将帮助你简化你的网络请求并带来大量的额外好处。
感谢你的阅读,我希望你喜欢这个:-)

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值