zoukankan      html  css  js  c++  java
  • volley介绍03

    ------------------------------------------------------------------------------

    转载:http://blog.csdn.net/crazy__chen/article/details/46486123

    ------------------------------------------------------------------------------

    在上一篇文章中,我们已经提到volley的使用方式和设计的整体思路,从这篇文章开始,我就要结合具体的源码来给大家说明volley功能的具体实现。

    我们第一个要介绍的类是Request<T>这个一个抽象类,我将Request称为一个请求,通过继承Request<T>来自定义request,为volley提供了更加灵活的接口。

    Request<T>中的泛型T,是指解析response以后的结果。在上一篇文章中我们知道,ResponseDelivery会把response分派给对应的request(中文翻译就是,把响应分派给对应的请求)。在我们定义的请求中,需要重写parseNetworkResponse(NetworkResponse response)这个方法,解析请求,解析出来的结果,就是T类型的。

    OK,我们现在来直接看源码。

    首先是一些属性

    /** 
     * Base class for all network requests. 
     * 请求基类 
     * @param <T> The type of parsed response this request expects. 
     * T为响应类型 
     */  
    public abstract class Request<T> implements Comparable<Request<T>> {  
      
        /** 
         * Default encoding for POST or PUT parameters. See {@link #getParamsEncoding()}. 
         * 默认编码 
         */  
        private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";  
      
        /** 
         * Supported request methods. 
         * 支持的请求方式 
         */  
        public interface Method {  
            int DEPRECATED_GET_OR_POST = -1;  
            int GET = 0;  
            int POST = 1;  
            int PUT = 2;  
            int DELETE = 3;  
            int HEAD = 4;  
            int OPTIONS = 5;  
            int TRACE = 6;  
            int PATCH = 7;  
        }  
      
        /**  
         * An event log tracing the lifetime of this request; for debugging. 
         * 用于跟踪请求的生存时间,用于调试  
         * */  
        private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null;  
      
        /** 
         * Request method of this request.  Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS, 
         * TRACE, and PATCH. 
         * 当前请求方式 
         */  
        private final int mMethod;  
      
        /**  
         * URL of this request.  
         * 请求地址  
         */  
        private final String mUrl;  
          
        /**  
         * The redirect url to use for 3xx http responses  
         * 重定向地址  
         */  
        private String mRedirectUrl;  
      
        /**  
         * The unique identifier of the request 
         * 该请求的唯一凭证  
         */  
        private String mIdentifier;  
      
        /**  
         * Default tag for {@link TrafficStats}. 
         * 流量统计标签  
         */  
        private final int mDefaultTrafficStatsTag;  
      
        /**  
         * Listener interface for errors. 
         * 错误监听器  
         */  
        private final Response.ErrorListener mErrorListener;  
      
        /**  
         * Sequence number of this request, used to enforce FIFO ordering. 
         * 请求序号,用于fifo算法  
         */  
        private Integer mSequence;  
      
        /**  
         * The request queue this request is associated with. 
         * 请求所在的请求队列  
         */  
        private RequestQueue mRequestQueue;  
      
        /**  
         * Whether or not responses to this request should be cached. 
         * 是否使用缓存响应请求  
         */  
        private boolean mShouldCache = true;  
      
        /**  
         * Whether or not this request has been canceled. 
         * 该请求是否被取消  
         */  
        private boolean mCanceled = false;  
      
        /**  
         * Whether or not a response has been delivered for this request yet. 
         * 该请求是否已经被响应  
         */  
        private boolean mResponseDelivered = false;  
          
        /** 
         * A cheap variant of request tracing used to dump slow requests. 
         * 一个简单的变量,跟踪请求,用来抛弃过慢的请求 
         * 请求产生时间  
         */  
        private long mRequestBirthTime = 0;  
      
        /** Threshold at which we should log the request (even when debug logging is not enabled). */  
        private static final long SLOW_REQUEST_THRESHOLD_MS = 3000;  
      
        /**  
         * The retry policy for this request. 
         * 请求重试策略  
         */  
        private RetryPolicy mRetryPolicy;  
      
        /** 
         * When a request can be retrieved from cache but must be refreshed from 
         * the network, the cache entry will be stored here so that in the event of 
         * a "Not Modified" response, we can be sure it hasn't been evicted from cache. 
         * 缓存记录。当请求可以从缓存中获得响应,但必须从网络上更新时。我们保留这个缓存记录,所以一旦从网络上获得的响应带有Not Modified 
         * (没有更新)时,来保证这个缓存没有被回收. 
         */  
        private Cache.Entry mCacheEntry = null;  
      
        /** 
         *  An opaque token tagging this request; used for bulk cancellation. 
         *  用于自定义标记,可以理解为用于请求的分类  
         */  
        private Object mTag;  

      

    不得不说,上面的属性非常之多(我都有写注释),但是每个属性都有其相应的用处,而且有些属性的设置,是我们不大能考虑到的。我要来介绍一下。

    1,DEFAULT_PARAMS_ENCODING = "UTF-8"默认编码

    2,mMethod请求方式

    3,mUrl请求地址

    4,mRedirectUrl重定向地址,这个地址在网络响应状态码是403时,会被使用

    5,mSequence序列号,就是这个request在队列中的序号(不是顺序)

    6,mRequestQueue请求所在的请求队列 

    7,mErrorListener错误监听器

    9,mShouldCache是否缓存,如果这个属性为真,就会先视图从缓存中查询请求结果

    10,mCacheEntry缓存记录,这个记录用于缓存响应头等

    11,mTag自定义标记,用户可以给一些请求自定义标记,使用这些标记,我们可以统一管理用于这些标记的请求,例如统一取消它们

    接下来看构造方法

    /** 
         * Creates a new request with the given method (one of the values from {@link Method}), 
         * URL, and error listener.  Note that the normal response listener is not provided here as 
         * delivery of responses is provided by subclasses, who have a better idea of how to deliver 
         * an already-parsed response. 
         * 根据请求方式,创建新的请求(需要地址,错误监听器等参数)  
         */  
        public Request(int method, String url, Response.ErrorListener listener) {  
            mMethod = method;  
            mUrl = url;  
            mIdentifier = createIdentifier(method, url);//为请求创建唯一凭证  
            mErrorListener = listener;//设定监听器  
            setRetryPolicy(new DefaultRetryPolicy());//设置默认重试策略  
      
            mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);//设置流量标志  
        }  
    

      

    首先是请求方式,请求地址的设定,这是作为一个请求必须有的。然后是监听器的设定,注意这里只是这是了ErrorListner,说明errorListener是必须的,但是正确响应,我们有可能不处理。这样设定是合理的,因为出错了,我们必须处理,至于请求成功,我们可以不处理。那么我们想处理成功的请求怎么办呢,这需要在子类中重写构造方法(例如StringRequest)。

    然后是创建了一个唯一凭证

    /** 
         *  sha1(Request:method:url:timestamp:counter) 
         * @param method http method 
         * @param url               http request url 
         * @return sha1 hash string 
         * 利用请求方式和地址,进行sha1加密,创建该请求的唯一凭证 
         */  
        private static String createIdentifier(final int method, final String url) {  
            return InternalUtils.sha1Hash("Request:" + method + ":" + url +  
                    ":" + System.currentTimeMillis() + ":" + (sCounter++));  
        }  

     

    由上面的方法可以看出,这个凭证和当前时间有关,因此是独一无二的

    接着是设置重试策略,这个类等下再介绍,接下来是流量标志的设置,所谓流量标志,是用于调试日志记录的,不是重点

     
    /** 
         * @return The hashcode of the URL's host component, or 0 if there is none. 
         * 返回url的host(主机地址)部分的hashcode,如果host不存在,返回0 
         */  
        private static int findDefaultTrafficStatsTag(String url) {  
            if (!TextUtils.isEmpty(url)) {  
                Uri uri = Uri.parse(url);  
                if (uri != null) {  
                    String host = uri.getHost();  
                    if (host != null) {  
                        return host.hashCode();  
                    }  
                }  
            }  
            return 0;  
        }  
    

      

    我们再回过头来看这个重试策略。

    volley为重试策略专门定义了一个类,这样我们就可以根据需要实现自己的重试策略了,至于源码内部,为我们提供了一个默认的重试策略DefaultRetryPolicy()

    要介绍重试策略,我们先看重试策略的基类RetryPolicy

    /** 
     * Retry policy for a request. 
     * 请求重试策略类 
     */  
    public interface RetryPolicy {  
      
        /** 
         * Returns the current timeout (used for logging). 
         * 获得当前时间,用于日志 
         */  
        public int getCurrentTimeout();  
      
        /** 
         * Returns the current retry count (used for logging). 
         * 返回当前重试次数,用于日志 
         */  
        public int getCurrentRetryCount();  
      
        /** 
         * Prepares for the next retry by applying a backoff to the timeout. 
         * @param error The error code of the last attempt. 
         * @throws VolleyError In the event that the retry could not be performed (for example if we 
         * ran out of attempts), the passed in error is thrown. 
         * 重试实现 
         */  
        public void retry(VolleyError error) throws VolleyError;  
    }  

    重要的是retry()这个方法,我们来看DefaultRetryPolicy里面这个方法的具体实现

    /** 
         * Prepares for the next retry by applying a backoff to the timeout. 
         * @param error The error code of the last attempt. 
         */  
        @Override  
        public void retry(VolleyError error) throws VolleyError {  
            mCurrentRetryCount++;//当前重试次数  
            mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);//当前超出时间  
            if (!hasAttemptRemaining()) {//是否已经到达最大重试次数  
                throw error;  
            }  
        }  
      
        /** 
         * Returns true if this policy has attempts remaining, false otherwise. 
         * 是否还重试 
         */  
        protected boolean hasAttemptRemaining() {  
            return mCurrentRetryCount <= mMaxNumRetries;//最大重试次数  
        }  

    可以看到,在默认的重试策略中,只是简单地统计了重试的次数,然后,在超出最大次数以后,抛出异常。

    就这么简单,那么究竟volley是怎么实现重试的呢?

    实际上,当从队列中取出一个request去进行网络请求的时候,我们是写在一个死循环里面的(在以后的代码可以看到,这样不贴出来以免类过多造成困扰)。

    一旦请求失败,就会调用上面的retry()方法,但是没有跳出循环。直到请求成功获得response,才return。如果一直请求失败,根据上面的重试策略,最后会抛出VolleyError异常,这个异常不处理,而是通过throws向外抛,从而结束死循环。

    从程序设计的角度来说,通过抛出异常结束死循环,显得不是那么的优雅(通常我们用设置标记的方法结束循环),但是在volley中使用了这个方式,原因是对于这个异常,要交给程序员自己处理,虽然这样使异常传递的过程变得复杂,但是增加了程序的灵活性。

    最终的异常,我们会在Request<T>的parseNetworkError()和deliverError()方法里面处理,parseNetworkError()用于解析Volleyerror,deliverError()方法回调了上面一开始就提到的ErrorListener

    /** 
         * Subclasses can override this method to parse 'networkError' and return a more specific error. 
         * 
         * <p>The default implementation just returns the passed 'networkError'.</p> 
         * 
         * @param volleyError the error retrieved from the network 
         * @return an NetworkError augmented with additional information 
         * 解析网络错误 
         */  
        public VolleyError parseNetworkError(VolleyError volleyError) {  
            return volleyError;  
        }  
      
        /** 
         * Delivers error message to the ErrorListener that the Request was 
         * initialized with. 
         * 
         * @param error Error details 
         * 分发网络错误 
         */  
        public void deliverError(VolleyError error) {  
            if (mErrorListener != null) {  
                mErrorListener.onErrorResponse(error);  
            }  
        }  

    其实除了上面两个处理错误的方法,还有两个方法用于处理成功响应,是必须要继承的

    /** 
         * Subclasses must implement this to parse the raw network response 
         * and return an appropriate response type. This method will be 
         * called from a worker thread.  The response will not be delivered 
         * if you return null. 
         * @param response Response from the network 
         * @return The parsed response, or null in the case of an error 
         * 解析响应 
         */  
        public abstract Response<T> parseNetworkResponse(NetworkResponse response);  
    <pre name="code" class="java">/** 
         * Subclasses must implement this to perform delivery of the parsed 
         * response to their listeners.  The given response is guaranteed to 
         * be non-null; responses that fail to parse are not delivered. 
         * @param response The parsed response returned by 
         * {@link #parseNetworkResponse(NetworkResponse)} 
         * 分发响应 
         */  
        public abstract void deliverResponse(T response);  

    parseNetworkResponse(NetworkResponse response)用于将网络response解析为本地response,解析出来的response,会交给deliverResponse(T response)方法。

    为什么要解析,其实上面已经说过,要将结果解析为T类型。至于这两个方法,其实是在ResponseDelivery响应分发器里面调用的。

    看完初始化方法,我们来看结束请求的方法finish(),有时候我们想要主动终止请求,例如停止下载文件,又或者请求已经成功了,我们从队列中去除这个请求

    /** 
         * Notifies the request queue that this request has finished (successfully or with error). 
         * 提醒请求队列,当前请求已经完成(失败或成功) 
         * <p>Also dumps all events from this request's event log; for debugging.</p> 
         *  
         */  
        public void finish(final String tag) {  
            if (mRequestQueue != null) {  
                mRequestQueue.finish(this);//该请求完成  
            }  
            if (MarkerLog.ENABLED) {//如果开启调试  
                final long threadId = Thread.currentThread().getId();//线程id  
                if (Looper.myLooper() != Looper.getMainLooper()) {//请求不是在主线程  
                    // If we finish marking off of the main thread, we need to  
                    // actually do it on the main thread to ensure correct ordering.  
                    //如果我们不是在主线程记录log,我们需要在主线程做这项工作来保证正确的顺序  
                    Handler mainThread = new Handler(Looper.getMainLooper());  
                    mainThread.post(new Runnable() {  
                        @Override  
                        public void run() {  
                            mEventLog.add(tag, threadId);  
                            mEventLog.finish(this.toString());  
                        }  
                    });  
                    return;  
                }  
                //如果在主线程,直接记录  
                mEventLog.add(tag, threadId);  
                mEventLog.finish(this.toString());  
            } else {//不开启调试  
                long requestTime = SystemClock.elapsedRealtime() - mRequestBirthTime;  
                if (requestTime >= SLOW_REQUEST_THRESHOLD_MS) {  
                    VolleyLog.d("%d ms: %s", requestTime, this.toString());  
                }  
            }  
        }   

    上面主要是做了一些日志记录的工作,最重要的是调用了mRequestQueue的finish()方法,来从队列中去除这个请求。

    看完上面的介绍以后,大家是否注意到,Request<T>继承了Comparable<Request<T>>接口,为什么要继承这个接口了,我们当然要来看compareTo()方法了

    /** 
         * Our comparator sorts from high to low priority, and secondarily by 
         * sequence number to provide FIFO ordering. 
         */  
        @Override  
        public int compareTo(Request<T> other) {  
            Priority left = this.getPriority();  
            Priority right = other.getPriority();  
      
            // High-priority requests are "lesser" so they are sorted to the front.  
            // Equal priorities are sorted by sequence number to provide FIFO ordering.  
            return left == right ?  
                    this.mSequence - other.mSequence :  
                    right.ordinal() - left.ordinal();  
        }   

    这个方法比较了两个请求的优先级,如果优先级相等,就按照顺序。

    实现这个接口的目的,正如上一篇文章提到的,有的请求比较重要,希望早点执行,也就是说让它排在请求队列的前头

    通过比较方法,我们就可以设定请求在请求队列中排队顺序的根据,从而让优先级高的排在前面。

    OK,Request<T>就基本介绍完了,当然有些属性,例如缓存mCacheEntry,mRedirectUrl重定向地址等我们还没有用到,我们先记住它们,在以后会使用到的。

    其实Request<T>类并不复杂,主要就是一些属性的设置,这些属性有的比较难考虑到,例如优先级,重定向地址,自定义标记,重试策略等。

    最后,我们通过StringRequest来看一下Request<T>类的具体实现

    /** 
     * A canned request for retrieving the response body at a given URL as a String. 
     */  
    public class StringRequest extends Request<String> {  
        private final Listener<String> mListener;  
      
        /** 
         * Creates a new request with the given method. 
         * 
         * @param method the request {@link Method} to use 
         * @param url URL to fetch the string at 
         * @param listener Listener to receive the String response 
         * @param errorListener Error listener, or null to ignore errors 
         */  
        public StringRequest(int method, String url, Listener<String> listener,  
                ErrorListener errorListener) {  
            super(method, url, errorListener);  
            mListener = listener;  
        }  
    

    上面的构造方法中,添加了一个新的接口Listener<String> listener,用于监听成功的response

    然后是parseNetworkResponse(NetworkResponse response),这个方法

    @Override  
        public Response<String> parseNetworkResponse(NetworkResponse response) {  
            String parsed;  
            try {  
                parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));  
            } catch (UnsupportedEncodingException e) {  
                parsed = new String(response.data);  
            }  
            return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));  
        }  

    可以看到,将NetworkResponse解析为String类型的了,然后再构造成对应的本地response

    @Override  
    public void deliverResponse(String response) {  
        mListener.onResponse(response);  
    }  

    至于deliverResponse(String response),则调用了构造方法里面要求的,新的监听器。

    到此为止,对于Request<T>的介绍就结束了,由于Request<T>和其他类的耦合并不是特别重,相信是比较容易理解。

    在下一篇文章中,我们会来看RequestQueue队列,看看这个队列的作用到底是什么,我们为什么要创建一个队列来保存request而不是直接每个request开启一个线程去加载网络数据。

  • 相关阅读:
    13、java中8中基本类型
    12、static final
    11、final详解
    10、java初始化顺序
    9、java中static详解
    9、接口和抽象类
    8、java内部类
    7、手工编译和运行时注意事项
    推荐10 款 SVG 动画的 JavaScript 库
    让优秀的文章脱颖而出---极客头条使用体验
  • 原文地址:https://www.cnblogs.com/aprz512/p/5316688.html
Copyright © 2011-2022 走看看