源码:

  1. /*
  2. * Copyright (C) 2011 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16.  
  17. package com.android.volley;
  18.  
  19. import android.net.TrafficStats;
  20. import android.net.Uri;
  21. import android.os.Handler;
  22. import android.os.Looper;
  23. import android.text.TextUtils;
  24. import com.android.volley.VolleyLog.MarkerLog;
  25.  
  26. import java.io.UnsupportedEncodingException;
  27. import java.net.URLEncoder;
  28. import java.util.Collections;
  29. import java.util.Map;
  30.  
  31. /**
  32. * Base class for all network requests.
  33. *
  34. * @param <T> The type of parsed response this request expects.
  35. */
  36. public abstract class Request<T> implements Comparable<Request<T>> {
  37.  
  38. /**
  39. * Default encoding for POST or PUT parameters. See {@link #getParamsEncoding()}.
  40. */
  41. private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
  42.  
  43. /**
  44. * Supported request methods.
  45. */
  46. public interface Method {
  47. int DEPRECATED_GET_OR_POST = -;
  48. int GET = ;
  49. int POST = ;
  50. int PUT = ;
  51. int DELETE = ;
  52. int HEAD = ;
  53. int OPTIONS = ;
  54. int TRACE = ;
  55. int PATCH = ;
  56. }
  57.  
  58. /** An event log tracing the lifetime of this request; for debugging. */
  59. private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null;
  60.  
  61. /**
  62. * Request method of this request. Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS,
  63. * TRACE, and PATCH.
  64. */
  65. private final int mMethod;
  66.  
  67. /** URL of this request. */
  68. private final String mUrl;
  69.  
  70. /** The redirect url to use for 3xx http responses */
  71. private String mRedirectUrl;
  72.  
  73. /** The unique identifier of the request */
  74. private String mIdentifier;
  75.  
  76. /** Default tag for {@link TrafficStats}. */
  77. private final int mDefaultTrafficStatsTag;
  78.  
  79. /** Listener interface for errors. */
  80. private Response.ErrorListener mErrorListener;
  81.  
  82. /** Sequence number of this request, used to enforce FIFO ordering. */
  83. private Integer mSequence;
  84.  
  85. /** The request queue this request is associated with. */
  86. private RequestQueue mRequestQueue;
  87.  
  88. /** Whether or not responses to this request should be cached. */
  89. private boolean mShouldCache = true;
  90.  
  91. /** Whether or not this request has been canceled. */
  92. private boolean mCanceled = false;
  93.  
  94. /** Whether or not a response has been delivered for this request yet. */
  95. private boolean mResponseDelivered = false;
  96.  
  97. /** The retry policy for this request. */
  98. private RetryPolicy mRetryPolicy;
  99.  
  100. /**
  101. * When a request can be retrieved from cache but must be refreshed from
  102. * the network, the cache entry will be stored here so that in the event of
  103. * a "Not Modified" response, we can be sure it hasn't been evicted from cache.
  104. */
  105. private Cache.Entry mCacheEntry = null;
  106.  
  107. /** An opaque token tagging this request; used for bulk cancellation. */
  108. private Object mTag;
  109.  
  110. /**
  111. * Creates a new request with the given URL and error listener. Note that
  112. * the normal response listener is not provided here as delivery of responses
  113. * is provided by subclasses, who have a better idea of how to deliver an
  114. * already-parsed response.
  115. *
  116. * @deprecated Use {@link #Request(int, String, com.android.volley.Response.ErrorListener)}.
  117. */
  118. @Deprecated
  119. public Request(String url, Response.ErrorListener listener) {
  120. this(Method.DEPRECATED_GET_OR_POST, url, listener);
  121. }
  122.  
  123. /**
  124. * Creates a new request with the given method (one of the values from {@link Method}),
  125. * URL, and error listener. Note that the normal response listener is not provided here as
  126. * delivery of responses is provided by subclasses, who have a better idea of how to deliver
  127. * an already-parsed response.
  128. */
  129. public Request(int method, String url, Response.ErrorListener listener) {
  130. mMethod = method;
  131. mUrl = url;
  132. mIdentifier = createIdentifier(method, url);
  133. mErrorListener = listener;
  134. setRetryPolicy(new DefaultRetryPolicy());
  135.  
  136. mDefaultTrafficStatsTag = findDefaultTrafficStatsTag(url);
  137. }
  138.  
  139. /**
  140. * Return the method for this request. Can be one of the values in {@link Method}.
  141. */
  142. public int getMethod() {
  143. return mMethod;
  144. }
  145.  
  146. /**
  147. * Set a tag on this request. Can be used to cancel all requests with this
  148. * tag by {@link RequestQueue#cancelAll(Object)}.
  149. *
  150. * @return This Request object to allow for chaining.
  151. */
  152. public Request<?> setTag(Object tag) {
  153. mTag = tag;
  154. return this;
  155. }
  156.  
  157. /**
  158. * Returns this request's tag.
  159. * @see Request#setTag(Object)
  160. */
  161. public Object getTag() {
  162. return mTag;
  163. }
  164.  
  165. /**
  166. * @return this request's {@link com.android.volley.Response.ErrorListener}.
  167. */
  168. public Response.ErrorListener getErrorListener() {
  169. return mErrorListener;
  170. }
  171.  
  172. /**
  173. * @return A tag for use with {@link TrafficStats#setThreadStatsTag(int)}
  174. */
  175. public int getTrafficStatsTag() {
  176. return mDefaultTrafficStatsTag;
  177. }
  178.  
  179. /**
  180. * @return The hashcode of the URL's host component, or 0 if there is none.
  181. */
  182. private static int findDefaultTrafficStatsTag(String url) {
  183. if (!TextUtils.isEmpty(url)) {
  184. Uri uri = Uri.parse(url);
  185. if (uri != null) {
  186. String host = uri.getHost();
  187. if (host != null) {
  188. return host.hashCode();
  189. }
  190. }
  191. }
  192. return ;
  193. }
  194.  
  195. /**
  196. * Sets the retry policy for this request.
  197. *
  198. * @return This Request object to allow for chaining.
  199. */
  200. public Request<?> setRetryPolicy(RetryPolicy retryPolicy) {
  201. mRetryPolicy = retryPolicy;
  202. return this;
  203. }
  204.  
  205. /**
  206. * Adds an event to this request's event log; for debugging.
  207. */
  208. public void addMarker(String tag) {
  209. if (MarkerLog.ENABLED) {
  210. mEventLog.add(tag, Thread.currentThread().getId());
  211. }
  212. }
  213.  
  214. /**
  215. * Notifies the request queue that this request has finished (successfully or with error).
  216. *
  217. * <p>Also dumps all events from this request's event log; for debugging.</p>
  218. */
  219. void finish(final String tag) {
  220. if (mRequestQueue != null) {
  221. mRequestQueue.finish(this);
  222. onFinish();
  223. }
  224. if (MarkerLog.ENABLED) {
  225. final long threadId = Thread.currentThread().getId();
  226. if (Looper.myLooper() != Looper.getMainLooper()) {
  227. // If we finish marking off of the main thread, we need to
  228. // actually do it on the main thread to ensure correct ordering.
  229. Handler mainThread = new Handler(Looper.getMainLooper());
  230. mainThread.post(new Runnable() {
  231. @Override
  232. public void run() {
  233. mEventLog.add(tag, threadId);
  234. mEventLog.finish(this.toString());
  235. }
  236. });
  237. return;
  238. }
  239.  
  240. mEventLog.add(tag, threadId);
  241. mEventLog.finish(this.toString());
  242. }
  243. }
  244.  
  245. /**
  246. * clear listeners when finished
  247. */
  248. protected void onFinish() {
  249. mErrorListener = null;
  250. }
  251.  
  252. /**
  253. * Associates this request with the given queue. The request queue will be notified when this
  254. * request has finished.
  255. *
  256. * @return This Request object to allow for chaining.
  257. */
  258. public Request<?> setRequestQueue(RequestQueue requestQueue) {
  259. mRequestQueue = requestQueue;
  260. return this;
  261. }
  262.  
  263. /**
  264. * Sets the sequence number of this request. Used by {@link RequestQueue}.
  265. *
  266. * @return This Request object to allow for chaining.
  267. */
  268. public final Request<?> setSequence(int sequence) {
  269. mSequence = sequence;
  270. return this;
  271. }
  272.  
  273. /**
  274. * Returns the sequence number of this request.
  275. */
  276. public final int getSequence() {
  277. if (mSequence == null) {
  278. throw new IllegalStateException("getSequence called before setSequence");
  279. }
  280. return mSequence;
  281. }
  282.  
  283. /**
  284. * Returns the URL of this request.
  285. */
  286. public String getUrl() {
  287. return (mRedirectUrl != null) ? mRedirectUrl : mUrl;
  288. }
  289.  
  290. /**
  291. * Returns the URL of the request before any redirects have occurred.
  292. */
  293. public String getOriginUrl() {
  294. return mUrl;
  295. }
  296.  
  297. /**
  298. * Returns the identifier of the request.
  299. */
  300. public String getIdentifier() {
  301. return mIdentifier;
  302. }
  303.  
  304. /**
  305. * Sets the redirect url to handle 3xx http responses.
  306. */
  307. public void setRedirectUrl(String redirectUrl) {
  308. mRedirectUrl = redirectUrl;
  309. }
  310.  
  311. /**
  312. * Returns the cache key for this request. By default, this is the URL.
  313. */
  314. public String getCacheKey() {
  315. return mMethod + ":" + mUrl;
  316. }
  317.  
  318. /**
  319. * Annotates this request with an entry retrieved for it from cache.
  320. * Used for cache coherency support.
  321. *
  322. * @return This Request object to allow for chaining.
  323. */
  324. public Request<?> setCacheEntry(Cache.Entry entry) {
  325. mCacheEntry = entry;
  326. return this;
  327. }
  328.  
  329. /**
  330. * Returns the annotated cache entry, or null if there isn't one.
  331. */
  332. public Cache.Entry getCacheEntry() {
  333. return mCacheEntry;
  334. }
  335.  
  336. /**
  337. * Mark this request as canceled. No callback will be delivered.
  338. */
  339. public void cancel() {
  340. mCanceled = true;
  341. }
  342.  
  343. /**
  344. * Returns true if this request has been canceled.
  345. */
  346. public boolean isCanceled() {
  347. return mCanceled;
  348. }
  349.  
  350. /**
  351. * Returns a list of extra HTTP headers to go along with this request. Can
  352. * throw {@link AuthFailureError} as authentication may be required to
  353. * provide these values.
  354. * @throws AuthFailureError In the event of auth failure
  355. */
  356. public Map<String, String> getHeaders() throws AuthFailureError {
  357. return Collections.emptyMap();
  358. }
  359.  
  360. /**
  361. * Returns a Map of POST parameters to be used for this request, or null if
  362. * a simple GET should be used. Can throw {@link AuthFailureError} as
  363. * authentication may be required to provide these values.
  364. *
  365. * <p>Note that only one of getPostParams() and getPostBody() can return a non-null
  366. * value.</p>
  367. * @throws AuthFailureError In the event of auth failure
  368. *
  369. * @deprecated Use {@link #getParams()} instead.
  370. */
  371. @Deprecated
  372. protected Map<String, String> getPostParams() throws AuthFailureError {
  373. return getParams();
  374. }
  375.  
  376. /**
  377. * Returns which encoding should be used when converting POST parameters returned by
  378. * {@link #getPostParams()} into a raw POST body.
  379. *
  380. * <p>This controls both encodings:
  381. * <ol>
  382. * <li>The string encoding used when converting parameter names and values into bytes prior
  383. * to URL encoding them.</li>
  384. * <li>The string encoding used when converting the URL encoded parameters into a raw
  385. * byte array.</li>
  386. * </ol>
  387. *
  388. * @deprecated Use {@link #getParamsEncoding()} instead.
  389. */
  390. @Deprecated
  391. protected String getPostParamsEncoding() {
  392. return getParamsEncoding();
  393. }
  394.  
  395. /**
  396. * @deprecated Use {@link #getBodyContentType()} instead.
  397. */
  398. @Deprecated
  399. public String getPostBodyContentType() {
  400. return getBodyContentType();
  401. }
  402.  
  403. /**
  404. * Returns the raw POST body to be sent.
  405. *
  406. * @throws AuthFailureError In the event of auth failure
  407. *
  408. * @deprecated Use {@link #getBody()} instead.
  409. */
  410. @Deprecated
  411. public byte[] getPostBody() throws AuthFailureError {
  412. // Note: For compatibility with legacy clients of volley, this implementation must remain
  413. // here instead of simply calling the getBody() function because this function must
  414. // call getPostParams() and getPostParamsEncoding() since legacy clients would have
  415. // overridden these two member functions for POST requests.
  416. Map<String, String> postParams = getPostParams();
  417. if (postParams != null && postParams.size() > ) {
  418. return encodeParameters(postParams, getPostParamsEncoding());
  419. }
  420. return null;
  421. }
  422.  
  423. /**
  424. * Returns a Map of parameters to be used for a POST or PUT request. Can throw
  425. * {@link AuthFailureError} as authentication may be required to provide these values.
  426. *
  427. * <p>Note that you can directly override {@link #getBody()} for custom data.</p>
  428. *
  429. * @throws AuthFailureError in the event of auth failure
  430. */
  431. protected Map<String, String> getParams() throws AuthFailureError {
  432. return null;
  433. }
  434.  
  435. /**
  436. * Returns which encoding should be used when converting POST or PUT parameters returned by
  437. * {@link #getParams()} into a raw POST or PUT body.
  438. *
  439. * <p>This controls both encodings:
  440. * <ol>
  441. * <li>The string encoding used when converting parameter names and values into bytes prior
  442. * to URL encoding them.</li>
  443. * <li>The string encoding used when converting the URL encoded parameters into a raw
  444. * byte array.</li>
  445. * </ol>
  446. */
  447. protected String getParamsEncoding() {
  448. return DEFAULT_PARAMS_ENCODING;
  449. }
  450.  
  451. /**
  452. * Returns the content type of the POST or PUT body.
  453. */
  454. public String getBodyContentType() {
  455. return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
  456. }
  457.  
  458. /**
  459. * Returns the raw POST or PUT body to be sent.
  460. *
  461. * <p>By default, the body consists of the request parameters in
  462. * application/x-www-form-urlencoded format. When overriding this method, consider overriding
  463. * {@link #getBodyContentType()} as well to match the new body format.
  464. *
  465. * @throws AuthFailureError in the event of auth failure
  466. */
  467. public byte[] getBody() throws AuthFailureError {
  468. Map<String, String> params = getParams();
  469. if (params != null && params.size() > ) {
  470. return encodeParameters(params, getParamsEncoding());
  471. }
  472. return null;
  473. }
  474.  
  475. /**
  476. * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
  477. */
  478. private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
  479. StringBuilder encodedParams = new StringBuilder();
  480. try {
  481. for (Map.Entry<String, String> entry : params.entrySet()) {
  482. encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
  483. encodedParams.append('=');
  484. encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
  485. encodedParams.append('&');
  486. }
  487. return encodedParams.toString().getBytes(paramsEncoding);
  488. } catch (UnsupportedEncodingException uee) {
  489. throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
  490. }
  491. }
  492.  
  493. /**
  494. * Set whether or not responses to this request should be cached.
  495. *
  496. * @return This Request object to allow for chaining.
  497. */
  498. public final Request<?> setShouldCache(boolean shouldCache) {
  499. mShouldCache = shouldCache;
  500. return this;
  501. }
  502.  
  503. /**
  504. * Returns true if responses to this request should be cached.
  505. */
  506. public final boolean shouldCache() {
  507. return mShouldCache;
  508. }
  509.  
  510. /**
  511. * Priority values. Requests will be processed from higher priorities to
  512. * lower priorities, in FIFO order.
  513. */
  514. public enum Priority {
  515. LOW,
  516. NORMAL,
  517. HIGH,
  518. IMMEDIATE
  519. }
  520.  
  521. /**
  522. * Returns the {@link Priority} of this request; {@link Priority#NORMAL} by default.
  523. */
  524. public Priority getPriority() {
  525. return Priority.NORMAL;
  526. }
  527.  
  528. /**
  529. * Returns the socket timeout in milliseconds per retry attempt. (This value can be changed
  530. * per retry attempt if a backoff is specified via backoffTimeout()). If there are no retry
  531. * attempts remaining, this will cause delivery of a {@link TimeoutError} error.
  532. */
  533. public final int getTimeoutMs() {
  534. return mRetryPolicy.getCurrentTimeout();
  535. }
  536.  
  537. /**
  538. * Returns the retry policy that should be used for this request.
  539. */
  540. public RetryPolicy getRetryPolicy() {
  541. return mRetryPolicy;
  542. }
  543.  
  544. /**
  545. * Mark this request as having a response delivered on it. This can be used
  546. * later in the request's lifetime for suppressing identical responses.
  547. */
  548. public void markDelivered() {
  549. mResponseDelivered = true;
  550. }
  551.  
  552. /**
  553. * Returns true if this request has had a response delivered for it.
  554. */
  555. public boolean hasHadResponseDelivered() {
  556. return mResponseDelivered;
  557. }
  558.  
  559. /**
  560. * Subclasses must implement this to parse the raw network response
  561. * and return an appropriate response type. This method will be
  562. * called from a worker thread. The response will not be delivered
  563. * if you return null.
  564. * @param response Response from the network
  565. * @return The parsed response, or null in the case of an error
  566. */
  567. abstract protected Response<T> parseNetworkResponse(NetworkResponse response);
  568.  
  569. /**
  570. * Subclasses can override this method to parse 'networkError' and return a more specific error.
  571. *
  572. * <p>The default implementation just returns the passed 'networkError'.</p>
  573. *
  574. * @param volleyError the error retrieved from the network
  575. * @return an NetworkError augmented with additional information
  576. */
  577. protected VolleyError parseNetworkError(VolleyError volleyError) {
  578. return volleyError;
  579. }
  580.  
  581. /**
  582. * Subclasses must implement this to perform delivery of the parsed
  583. * response to their listeners. The given response is guaranteed to
  584. * be non-null; responses that fail to parse are not delivered.
  585. * @param response The parsed response returned by
  586. * {@link #parseNetworkResponse(NetworkResponse)}
  587. */
  588. abstract protected void deliverResponse(T response);
  589.  
  590. /**
  591. * Delivers error message to the ErrorListener that the Request was
  592. * initialized with.
  593. *
  594. * @param error Error details
  595. */
  596. public void deliverError(VolleyError error) {
  597. if (mErrorListener != null) {
  598. mErrorListener.onErrorResponse(error);
  599. }
  600. }
  601.  
  602. /**
  603. * Our comparator sorts from high to low priority, and secondarily by
  604. * sequence number to provide FIFO ordering.
  605. */
  606. @Override
  607. public int compareTo(Request<T> other) {
  608. Priority left = this.getPriority();
  609. Priority right = other.getPriority();
  610.  
  611. // High-priority requests are "lesser" so they are sorted to the front.
  612. // Equal priorities are sorted by sequence number to provide FIFO ordering.
  613. return left == right ?
  614. this.mSequence - other.mSequence :
  615. right.ordinal() - left.ordinal();
  616. }
  617.  
  618. @Override
  619. public String toString() {
  620. String trafficStatsTag = "0x" + Integer.toHexString(getTrafficStatsTag());
  621. return (mCanceled ? "[X] " : "[ ] ") + getUrl() + " " + trafficStatsTag + " "
  622. + getPriority() + " " + mSequence;
  623. }
  624.  
  625. private static long sCounter;
  626. /**
  627. * sha1(Request:method:url:timestamp:counter)
  628. * @param method http method
  629. * @param url http request url
  630. * @return sha1 hash string
  631. */
  632. private static String createIdentifier(final int method, final String url) {
  633. return InternalUtils.sha1Hash("Request:" + method + ":" + url +
  634. ":" + System.currentTimeMillis() + ":" + (sCounter++));
  635. }
  636. }

Request

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

首先是一些属性

  1. /**
  2. * Base class for all network requests.
  3. * 请求基类
  4. * @param <T> The type of parsed response this request expects.
  5. * T为响应类型
  6. */
  7. public abstract class Request<T> implements Comparable<Request<T>> {
  8.  
  9. /**
  10. * Default encoding for POST or PUT parameters. See {@link #getParamsEncoding()}.
  11. * 默认编码
  12. */
  13. private static final String DEFAULT_PARAMS_ENCODING = "UTF-8";
  14.  
  15. /**
  16. * Supported request methods.
  17. * 支持的请求方式
  18. */
  19. public interface Method {
  20. int DEPRECATED_GET_OR_POST = -;
  21. int GET = ;
  22. int POST = ;
  23. int PUT = ;
  24. int DELETE = ;
  25. int HEAD = ;
  26. int OPTIONS = ;
  27. int TRACE = ;
  28. int PATCH = ;
  29. }
  30.  
  31. /**
  32. * An event log tracing the lifetime of this request; for debugging.
  33. * 用于跟踪请求的生存时间,用于调试
  34. * */
  35. private final MarkerLog mEventLog = MarkerLog.ENABLED ? new MarkerLog() : null;
  36.  
  37. /**
  38. * Request method of this request. Currently supports GET, POST, PUT, DELETE, HEAD, OPTIONS,
  39. * TRACE, and PATCH.
  40. * 当前请求方式
  41. */
  42. private final int mMethod;
  43.  
  44. /**
  45. * URL of this request.
  46. * 请求地址
  47. */
  48. private final String mUrl;
  49.  
  50. /**
  51. * The redirect url to use for 3xx http responses
  52. * 重定向地址
  53. */
  54. private String mRedirectUrl;
  55.  
  56. /**
  57. * The unique identifier of the request
  58. * 该请求的唯一凭证
  59. */
  60. private String mIdentifier;
  61.  
  62. /**
  63. * Default tag for {@link TrafficStats}.
  64. * 流量统计标签
  65. */
  66. private final int mDefaultTrafficStatsTag;
  67.  
  68. /**
  69. * Listener interface for errors.
  70. * 错误监听器
  71. */
  72. private final Response.ErrorListener mErrorListener;
  73.  
  74. /**
  75. * Sequence number of this request, used to enforce FIFO ordering.
  76. * 请求序号,用于fifo算法
  77. */
  78. private Integer mSequence;
  79.  
  80. /**
  81. * The request queue this request is associated with.
  82. * 请求所在的请求队列
  83. */
  84. private RequestQueue mRequestQueue;
  85.  
  86. /**
  87. * Whether or not responses to this request should be cached.
  88. * 是否使用缓存响应请求
  89. */
  90. private boolean mShouldCache = true;
  91.  
  92. /**
  93. * Whether or not this request has been canceled.
  94. * 该请求是否被取消
  95. */
  96. private boolean mCanceled = false;
  97.  
  98. /**
  99. * Whether or not a response has been delivered for this request yet.
  100. * 该请求是否已经被响应
  101. */
  102. private boolean mResponseDelivered = false;
  103.  
  104. /**
  105. * A cheap variant of request tracing used to dump slow requests.
  106. * 一个简单的变量,跟踪请求,用来抛弃过慢的请求
  107. * 请求产生时间
  108. */
  109. private long mRequestBirthTime = ;
  110.  
  111. /** Threshold at which we should log the request (even when debug logging is not enabled). */
  112. private static final long SLOW_REQUEST_THRESHOLD_MS = ;
  113.  
  114. /**
  115. * The retry policy for this request.
  116. * 请求重试策略
  117. */
  118. private RetryPolicy mRetryPolicy;
  119.  
  120. /**
  121. * When a request can be retrieved from cache but must be refreshed from
  122. * the network, the cache entry will be stored here so that in the event of
  123. * a "Not Modified" response, we can be sure it hasn't been evicted from cache.
  124. * 缓存记录。当请求可以从缓存中获得响应,但必须从网络上更新时。我们保留这个缓存记录,所以一旦从网络上获得的响应带有Not Modified
  125. * (没有更新)时,来保证这个缓存没有被回收.
  126. */
  127. private Cache.Entry mCacheEntry = null;
  128.  
  129. /**
  130. * An opaque token tagging this request; used for bulk cancellation.
  131. * 用于自定义标记,可以理解为用于请求的分类
  132. */
  133. private Object mTag;

接下来看构造方法

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

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

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

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

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

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

  1. /**
  2. * @return The hashcode of the URL's host component, or 0 if there is none.
  3. * 返回url的host(主机地址)部分的hashcode,如果host不存在,返回0
  4. */
  5. private static int findDefaultTrafficStatsTag(String url) {
  6. if (!TextUtils.isEmpty(url)) {
  7. Uri uri = Uri.parse(url);
  8. if (uri != null) {
  9. String host = uri.getHost();
  10. if (host != null) {
  11. return host.hashCode();
  12. }
  13. }
  14. }
  15. return ;
  16. }

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

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

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

  1. /**
  2. * Retry policy for a request.
  3. * 请求重试策略类
  4. */
  5. public interface RetryPolicy {
  6.  
  7. /**
  8. * Returns the current timeout (used for logging).
  9. * 获得当前时间,用于日志
  10. */
  11. public int getCurrentTimeout();
  12.  
  13. /**
  14. * Returns the current retry count (used for logging).
  15. * 返回当前重试次数,用于日志
  16. */
  17. public int getCurrentRetryCount();
  18.  
  19. /**
  20. * Prepares for the next retry by applying a backoff to the timeout.
  21. * @param error The error code of the last attempt.
  22. * @throws VolleyError In the event that the retry could not be performed (for example if we
  23. * ran out of attempts), the passed in error is thrown.
  24. * 重试实现
  25. */
  26. public void retry(VolleyError error) throws VolleyError;
  27. }

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

  1. /**
  2. * Prepares for the next retry by applying a backoff to the timeout.
  3. * @param error The error code of the last attempt.
  4. */
  5. @Override
  6. public void retry(VolleyError error) throws VolleyError {
  7. mCurrentRetryCount++;//当前重试次数
  8. mCurrentTimeoutMs += (mCurrentTimeoutMs * mBackoffMultiplier);//当前超出时间
  9. if (!hasAttemptRemaining()) {//是否已经到达最大重试次数
  10. throw error;
  11. }
  12. }
  13.  
  14. /**
  15. * Returns true if this policy has attempts remaining, false otherwise.
  16. * 是否还重试
  17. */
  18. protected boolean hasAttemptRemaining() {
  19. return mCurrentRetryCount <= mMaxNumRetries;//最大重试次数
  20. }

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

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

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

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

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

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

  1. /**
  2. * Subclasses can override this method to parse 'networkError' and return a more specific error.
  3. *
  4. * <p>The default implementation just returns the passed 'networkError'.</p>
  5. *
  6. * @param volleyError the error retrieved from the network
  7. * @return an NetworkError augmented with additional information
  8. * 解析网络错误
  9. */
  10. public VolleyError parseNetworkError(VolleyError volleyError) {
  11. return volleyError;
  12. }
  13.  
  14. /**
  15. * Delivers error message to the ErrorListener that the Request was
  16. * initialized with.
  17. *
  18. * @param error Error details
  19. * 分发网络错误
  20. */
  21. public void deliverError(VolleyError error) {
  22. if (mErrorListener != null) {
  23. mErrorListener.onErrorResponse(error);
  24. }
  25. }

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

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

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

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

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

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

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

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

  1. /**
  2. * Our comparator sorts from high to low priority, and secondarily by
  3. * sequence number to provide FIFO ordering.
  4. */
  5. @Override
  6. public int compareTo(Request<T> other) {
  7. Priority left = this.getPriority();
  8. Priority right = other.getPriority();
  9.  
  10. // High-priority requests are "lesser" so they are sorted to the front.
  11. // Equal priorities are sorted by sequence number to provide FIFO ordering.
  12. return left == right ?
  13. this.mSequence - other.mSequence :
  14. right.ordinal() - left.ordinal();
  15. }

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

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

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

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

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

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

  1. /**
  2. * A canned request for retrieving the response body at a given URL as a String.
  3. */
  4. public class StringRequest extends Request<String> {
  5. private final Listener<String> mListener;
  6.  
  7. /**
  8. * Creates a new request with the given method.
  9. *
  10. * @param method the request {@link Method} to use
  11. * @param url URL to fetch the string at
  12. * @param listener Listener to receive the String response
  13. * @param errorListener Error listener, or null to ignore errors
  14. */
  15. public StringRequest(int method, String url, Listener<String> listener,
  16. ErrorListener errorListener) {
  17. super(method, url, errorListener);
  18. mListener = listener;
  19. }

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

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

  1. @Override
  2. public Response<String> parseNetworkResponse(NetworkResponse response) {
  3. String parsed;
  4. try {
  5. parsed = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
  6. } catch (UnsupportedEncodingException e) {
  7. parsed = new String(response.data);
  8. }
  9. return Response.success(parsed, HttpHeaderParser.parseCacheHeaders(response));
  10. }

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

  1. @Override
  2. public void deliverResponse(String response) {
  3. mListener.onResponse(response);
  4. }

至于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. localStorage注册页面A注册数据在本地储存并在B页面打开

    如题目的这么一个问题, A页面代码 <!DOCTYPE html> <html lang="en"> <head> <meta chars ...

  2. [BZOJ 2894]世界线

    传送门 \(\color{green}{solution}\) 在开这道题之前建议先看看3756:pty的字符串,然后你会发现这题就很zz了. 当然,作为一名合格的博主,我还是应该写点什么的 首先,我 ...

  3. 【学习小记】KD-Tree

    Preface 听说KD树实在是个大神器 可以解决多维空间多维偏序点权和,可以求某个点的空间最近最远点 就二维平面上的来说,复杂度在\(O(n\log n)\)到\(O(n\sqrt n)\)不等 嫌 ...

  4. winform两个窗体之间传值(C#委托事件实现)

    委托 定义一个委托,声明一个委托变量,然后让变量去做方法应该做的事. 委托是一个类型 事件是委托变量实现的 经典例子:两个winform窗体传值 定义两个窗体:form1和form2 form1上有一 ...

  5. 关于如何用js完成全选反选框等内容

    在学习js过程中按照视频写了这个页面 可以在点上面全选/全不选时全部选中或者取消 在单击下面的单选框时上面的全选会根据下面的单选框进行相应的调整 功能比较完善 以下是代码 <!DOCTYPE h ...

  6. Mac下Homebrew安装的软件放在什么地方

    一般情况是这么操作的: 1.通过brew install安装应用最先是放在/usr/local/Cellar/目录下. 2.有些应用会自动创建软链接放在/usr/bin或者/usr/sbin,同时也会 ...

  7. JAVA练手--String

    package tet; public class kk { public static void main(String[] args) { //1. { String Stra = "1 ...

  8. java并发编程(7)构建自定义同步工具及条件队列

    构建自定义同步工具 一.通过轮询与休眠的方式实现简单的有界缓存 public void put(V v) throws InterruptedException { while (true) { // ...

  9. html锚点使用示例

    <html> <body> <h1>HTML 教程目录</h1> <ul> <li><a href="#C1&q ...

  10. Java学习--Calendar 类的应用

    Calendar 类的应用 Date 类最主要的作用就是获得当前时间,同时这个类里面也具有设置时间以及一些其他的功能,但是由于本身设计的问题,这些方法却遭到众多批评,不建议使用,更推荐使用 Calen ...