源码:

 /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.android.volley; import android.net.TrafficStats;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import com.android.volley.VolleyLog.MarkerLog; import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.Map; /**
* Base class for all network requests.
*
* @param <T> The type of parsed response this request expects.
*/
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 = -;
int GET = ;
int POST = ;
int PUT = ;
int DELETE = ;
int HEAD = ;
int OPTIONS = ;
int TRACE = ;
int PATCH = ;
} /** 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 Response.ErrorListener mErrorListener; /** Sequence number of this request, used to enforce FIFO ordering. */
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; /** 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.
*/
private Cache.Entry mCacheEntry = null; /** An opaque token tagging this request; used for bulk cancellation. */
private Object mTag; /**
* Creates a new request with the given 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.
*
* @deprecated Use {@link #Request(int, String, com.android.volley.Response.ErrorListener)}.
*/
@Deprecated
public Request(String url, Response.ErrorListener listener) {
this(Method.DEPRECATED_GET_OR_POST, url, listener);
} /**
* 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);
} /**
* Return the method for this request. Can be one of the values in {@link Method}.
*/
public int getMethod() {
return mMethod;
} /**
* Set a tag on this request. Can be used to cancel all requests with this
* tag by {@link RequestQueue#cancelAll(Object)}.
*
* @return This Request object to allow for chaining.
*/
public Request<?> setTag(Object tag) {
mTag = tag;
return this;
} /**
* Returns this request's tag.
* @see Request#setTag(Object)
*/
public Object getTag() {
return mTag;
} /**
* @return this request's {@link com.android.volley.Response.ErrorListener}.
*/
public Response.ErrorListener getErrorListener() {
return mErrorListener;
} /**
* @return A tag for use with {@link TrafficStats#setThreadStatsTag(int)}
*/
public int getTrafficStatsTag() {
return mDefaultTrafficStatsTag;
} /**
* @return The hashcode of the URL's host component, or 0 if there is none.
*/
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 ;
} /**
* Sets the retry policy for this request.
*
* @return This Request object to allow for chaining.
*/
public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
mRetryPolicy = retryPolicy;
return this;
} /**
* Adds an event to this request's event log; for debugging.
*/
public void addMarker(String tag) {
if (MarkerLog.ENABLED) {
mEventLog.add(tag, Thread.currentThread().getId());
}
} /**
* 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>
*/
void finish(final String tag) {
if (mRequestQueue != null) {
mRequestQueue.finish(this);
onFinish();
}
if (MarkerLog.ENABLED) {
final long threadId = Thread.currentThread().getId();
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.
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());
}
} /**
* clear listeners when finished
*/
protected void onFinish() {
mErrorListener = null;
} /**
* Associates this request with the given queue. The request queue will be notified when this
* request has finished.
*
* @return This Request object to allow for chaining.
*/
public Request<?> setRequestQueue(RequestQueue requestQueue) {
mRequestQueue = requestQueue;
return this;
} /**
* Sets the sequence number of this request. Used by {@link RequestQueue}.
*
* @return This Request object to allow for chaining.
*/
public final Request<?> setSequence(int sequence) {
mSequence = sequence;
return this;
} /**
* Returns the sequence number of this request.
*/
public final int getSequence() {
if (mSequence == null) {
throw new IllegalStateException("getSequence called before setSequence");
}
return mSequence;
} /**
* Returns the URL of this request.
*/
public String getUrl() {
return (mRedirectUrl != null) ? mRedirectUrl : mUrl;
} /**
* Returns the URL of the request before any redirects have occurred.
*/
public String getOriginUrl() {
return mUrl;
} /**
* Returns the identifier of the request.
*/
public String getIdentifier() {
return mIdentifier;
} /**
* Sets the redirect url to handle 3xx http responses.
*/
public void setRedirectUrl(String redirectUrl) {
mRedirectUrl = redirectUrl;
} /**
* Returns the cache key for this request. By default, this is the URL.
*/
public String getCacheKey() {
return mMethod + ":" + mUrl;
} /**
* Annotates this request with an entry retrieved for it from cache.
* Used for cache coherency support.
*
* @return This Request object to allow for chaining.
*/
public Request<?> setCacheEntry(Cache.Entry entry) {
mCacheEntry = entry;
return this;
} /**
* Returns the annotated cache entry, or null if there isn't one.
*/
public Cache.Entry getCacheEntry() {
return mCacheEntry;
} /**
* Mark this request as canceled. No callback will be delivered.
*/
public void cancel() {
mCanceled = true;
} /**
* Returns true if this request has been canceled.
*/
public boolean isCanceled() {
return mCanceled;
} /**
* Returns a list of extra HTTP headers to go along with this request. Can
* throw {@link AuthFailureError} as authentication may be required to
* provide these values.
* @throws AuthFailureError In the event of auth failure
*/
public Map<String, String> getHeaders() throws AuthFailureError {
return Collections.emptyMap();
} /**
* Returns a Map of POST parameters to be used for this request, or null if
* a simple GET should be used. Can throw {@link AuthFailureError} as
* authentication may be required to provide these values.
*
* <p>Note that only one of getPostParams() and getPostBody() can return a non-null
* value.</p>
* @throws AuthFailureError In the event of auth failure
*
* @deprecated Use {@link #getParams()} instead.
*/
@Deprecated
protected Map<String, String> getPostParams() throws AuthFailureError {
return getParams();
} /**
* Returns which encoding should be used when converting POST parameters returned by
* {@link #getPostParams()} into a raw POST body.
*
* <p>This controls both encodings:
* <ol>
* <li>The string encoding used when converting parameter names and values into bytes prior
* to URL encoding them.</li>
* <li>The string encoding used when converting the URL encoded parameters into a raw
* byte array.</li>
* </ol>
*
* @deprecated Use {@link #getParamsEncoding()} instead.
*/
@Deprecated
protected String getPostParamsEncoding() {
return getParamsEncoding();
} /**
* @deprecated Use {@link #getBodyContentType()} instead.
*/
@Deprecated
public String getPostBodyContentType() {
return getBodyContentType();
} /**
* Returns the raw POST body to be sent.
*
* @throws AuthFailureError In the event of auth failure
*
* @deprecated Use {@link #getBody()} instead.
*/
@Deprecated
public byte[] getPostBody() throws AuthFailureError {
// Note: For compatibility with legacy clients of volley, this implementation must remain
// here instead of simply calling the getBody() function because this function must
// call getPostParams() and getPostParamsEncoding() since legacy clients would have
// overridden these two member functions for POST requests.
Map<String, String> postParams = getPostParams();
if (postParams != null && postParams.size() > ) {
return encodeParameters(postParams, getPostParamsEncoding());
}
return null;
} /**
* Returns a Map of parameters to be used for a POST or PUT request. Can throw
* {@link AuthFailureError} as authentication may be required to provide these values.
*
* <p>Note that you can directly override {@link #getBody()} for custom data.</p>
*
* @throws AuthFailureError in the event of auth failure
*/
protected Map<String, String> getParams() throws AuthFailureError {
return null;
} /**
* Returns which encoding should be used when converting POST or PUT parameters returned by
* {@link #getParams()} into a raw POST or PUT body.
*
* <p>This controls both encodings:
* <ol>
* <li>The string encoding used when converting parameter names and values into bytes prior
* to URL encoding them.</li>
* <li>The string encoding used when converting the URL encoded parameters into a raw
* byte array.</li>
* </ol>
*/
protected String getParamsEncoding() {
return DEFAULT_PARAMS_ENCODING;
} /**
* Returns the content type of the POST or PUT body.
*/
public String getBodyContentType() {
return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
} /**
* Returns the raw POST or PUT body to be sent.
*
* <p>By default, the body consists of the request parameters in
* application/x-www-form-urlencoded format. When overriding this method, consider overriding
* {@link #getBodyContentType()} as well to match the new body format.
*
* @throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
Map<String, String> params = getParams();
if (params != null && params.size() > ) {
return encodeParameters(params, getParamsEncoding());
}
return null;
} /**
* Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
*/
private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
StringBuilder encodedParams = new StringBuilder();
try {
for (Map.Entry<String, String> entry : params.entrySet()) {
encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
encodedParams.append('=');
encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
encodedParams.append('&');
}
return encodedParams.toString().getBytes(paramsEncoding);
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
}
} /**
* Set whether or not responses to this request should be cached.
*
* @return This Request object to allow for chaining.
*/
public final Request<?> setShouldCache(boolean shouldCache) {
mShouldCache = shouldCache;
return this;
} /**
* Returns true if responses to this request should be cached.
*/
public final boolean shouldCache() {
return mShouldCache;
} /**
* Priority values. Requests will be processed from higher priorities to
* lower priorities, in FIFO order.
*/
public enum Priority {
LOW,
NORMAL,
HIGH,
IMMEDIATE
} /**
* Returns the {@link Priority} of this request; {@link Priority#NORMAL} by default.
*/
public Priority getPriority() {
return Priority.NORMAL;
} /**
* Returns the socket timeout in milliseconds per retry attempt. (This value can be changed
* per retry attempt if a backoff is specified via backoffTimeout()). If there are no retry
* attempts remaining, this will cause delivery of a {@link TimeoutError} error.
*/
public final int getTimeoutMs() {
return mRetryPolicy.getCurrentTimeout();
} /**
* Returns the retry policy that should be used for this request.
*/
public RetryPolicy getRetryPolicy() {
return mRetryPolicy;
} /**
* Mark this request as having a response delivered on it. This can be used
* later in the request's lifetime for suppressing identical responses.
*/
public void markDelivered() {
mResponseDelivered = true;
} /**
* Returns true if this request has had a response delivered for it.
*/
public boolean hasHadResponseDelivered() {
return mResponseDelivered;
} /**
* 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
*/
abstract protected Response<T> parseNetworkResponse(NetworkResponse response); /**
* 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
*/
protected VolleyError parseNetworkError(VolleyError volleyError) {
return volleyError;
} /**
* 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)}
*/
abstract protected void deliverResponse(T response); /**
* 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);
}
} /**
* 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();
} @Override
public String toString() {
String trafficStatsTag = "0x" + Integer.toHexString(getTrafficStatsTag());
return (mCanceled ? "[X] " : "[ ] ") + getUrl() + " " + trafficStatsTag + " "
+ getPriority() + " " + mSequence;
} private static long sCounter;
/**
* sha1(Request:method:url:timestamp:counter)
* @param method http method
* @param url http request url
* @return sha1 hash string
*/
private static String createIdentifier(final int method, final String url) {
return InternalUtils.sha1Hash("Request:" + method + ":" + url +
":" + System.currentTimeMillis() + ":" + (sCounter++));
}
}

Request

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

首先是一些属性

 /**
* 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 = -;
int GET = ;
int POST = ;
int PUT = ;
int DELETE = ;
int HEAD = ;
int OPTIONS = ;
int TRACE = ;
int PATCH = ;
} /**
* 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 = ; /** Threshold at which we should log the request (even when debug logging is not enabled). */
private static final long SLOW_REQUEST_THRESHOLD_MS = ; /**
* 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;

接下来看构造方法

/**
* 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 ;
}

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

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开启一个线程去加载网络数据。

volley5--Request<T>类的介绍的更多相关文章

  1. Session监听类HttpSessionListener介绍及在listener里取得request

    Session监听类HttpSessionListener介绍及在listener里取得request servlet-api.jar中提供了监听类HttpSessionListener,主要方法有两 ...

  2. oc-12-NSString 类简单介绍及用法

    // 11-[掌握]NSString 类简单介绍及用法 #import <Foundation/Foundation.h> int main(int argc, const char * ...

  3. 【Entity Framework】初级篇--ObjectContext、ObjectQuery、ObjectStateEntry、ObjectStateManager类的介绍

    本节,简单的介绍EF中的ObjectContext.ObjectQuery.ObjectStateEntry.ObjectStateManager这个几个比较重要的类,它们都位于System.Data ...

  4. Entity Framework 学习初级篇2--ObjectContext类的介绍

    转自:http://www.cnblogs.com/Tally/archive/2012/09/14/2685014.html 本节,简单的介绍EF中的ObjectContext.ObjectQuer ...

  5. CImage类的介绍与使用

    CImage类的介绍与使用 程序代码下载处:http://download.csdn.net/source/2098910 下载处:http://hi.baidu.com/wangleitongxin ...

  6. Entity Framework 学习初级篇2--ObjectContext、ObjectQuery、ObjectStateEntry、ObjectStateManager类的介绍

    本节,简单的介绍EF中的ObjectContext.ObjectQuery.ObjectStateEntry.ObjectStateManager这个几个比较重要的类,它们都位于System.Data ...

  7. JdbcTemolate类的介绍<一>

    JdbcTemolate类的介绍 JdbcTemplate是Spring JDBC的核心类,封装了常见的JDBC的用法,同时尽量避免常见的错误.该类简化JDBC的操作,我们只需要书写提供SQL的代码和 ...

  8. 【转】Spring学习---Bean配置的三种方式(XML、注解、Java类)介绍与对比

    [原文]https://www.toutiao.com/i6594205115605844493/ Spring学习Bean配置的三种方式(XML.注解.Java类)介绍与对比 本文将详细介绍Spri ...

  9. 设置定时任务(Timer类的介绍)

    设置定时任务(Timer类的介绍) 在我们的很多项目中,我们都须要用到定时任务,因此想借此博文来对定时任务进行一个介绍. 设置定时任务过程例如以下: 先new一个Timer对象 Timer timer ...

随机推荐

  1. OpenFoam+CFDEM+Liggghts安装耦合

    这里安装的时间节点为:2018.10.29,安装的是目前的最新版本CFDEM,支持到与OpenFoam-5.x的耦合. 1. 先安装openfoam:https://openfoam.org/down ...

  2. (五)Audio子系统之AudioRecord.stop

    在上一篇文章<(四)Audio子系统之AudioRecord.read>中已经介绍了AudioRecord如何获取音频数据,接下来,继续分析AudioRecord方法中的stop的实现 函 ...

  3. Scrapyd API的安装

    安装好了Scrapyd之后,我们可以直接请求它提供的API来获取当前主机的Scrapy任务运行状况.比如,某台主机的IP为192.168.1.1,则可以直接运行如下命令获取当前主机的所有Scrapy项 ...

  4. Kali/Ubuntu无法和物理机之间复制粘贴解决办法

    Vmware安装Linux,传统的vmtools已经被抛弃,当前建议使用Open-VM-tools 安装Open-VM-tools//Kali,Ubuntu: sudo apt install Ope ...

  5. typescript 入门

    为什么要使用typescript? 出现拼写错误,可以立即指出错误. 出现模块引入错误,立即指出错误. 出现函数.变量类型错误,立即指出错误. 在react组件中制定好了基本的props和state之 ...

  6. Jedis操作Redis--SortedSet类型 (会自然排序)

    /** * SortedSet(有序集合) * ZADD,ZCARD,ZCOUNT,ZINCRBY,ZRANGE,ZRANGEBYSCORE,ZRANK,ZREM,ZREMRANGEBYRANK,ZR ...

  7. SSM上传EXCLE到数据库 和 从数据库导出为EXCLE

    SSM上传EXCLE到数据库 和 从数据库导出为EXCLE package com.ABC.controller; import java.io.BufferedInputStream; import ...

  8. UI的线程问题:单线程原因及更新UI的四种方式

    1.UI线程为什么设计为单线程? UI控件的操作不是线程安全的,对于多线程并发访问的时候,如果使用加锁机制会导致: UI控件的操作变得很复杂. 加锁的操作必定会导致效率下降. 所以android系统在 ...

  9. Hadoop Gateway 部署

    1.集群的 hadoop-current hive-current spark-current copy 到 gateway 机器 2.集群的 hadoop-conf       hive-conf ...

  10. 【c++】字符串流输出恢复状态问题

    缘起 #include <iostream> #include <sstream> using namespace std; int main() { istringstrea ...