码迷,mamicode.com
首页 > 其他好文 > 详细

volley5--Request<T>类的介绍

时间:2017-10-04 21:35:57      阅读:381      评论:0      收藏:0      [点我收藏+]

标签:code   methods   traffic   param   out   unique   sso   actually   turned   

源码:

技术分享
  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 = -1;
 48         int GET = 0;
 49         int POST = 1;
 50         int PUT = 2;
 51         int DELETE = 3;
 52         int HEAD = 4;
 53         int OPTIONS = 5;
 54         int TRACE = 6;
 55         int PATCH = 7;
 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 0;
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() > 0) {
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() > 0) {
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

 

volley5--Request<T>类的介绍

标签:code   methods   traffic   param   out   unique   sso   actually   turned   

原文地址:http://www.cnblogs.com/ganchuanpu/p/7627180.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!