volley5--Request<T>类的介绍

源码:

  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

 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 = -1;  
 21         int GET = 0;  
 22         int POST = 1;  
 23         int PUT = 2;  
 24         int DELETE = 3;  
 25         int HEAD = 4;  
 26         int OPTIONS = 5;  
 27         int TRACE = 6;  
 28         int PATCH = 7;  
 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 = 0;  
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 = 3000;  
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;  

接下来看构造方法

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

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

 

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

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

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

 

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

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

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

 

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

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

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

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

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

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

 

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

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

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

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

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

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

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

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

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

 

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

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

 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()方法了

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

package com.example.kucun2.entity.data; import android.content.Context; import android.util.Log; import com.example.kucun2.entity.; import com.example.kucun2.function.MyAppFnction; import com.example.kucun2.function.TLSUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.lang.reflect.Type; import java.util.; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.X509TrustManager; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class Data { // 数据集合声明(保持原有属性名不变) public static SynchronizedList<Bancai> bancais = new SynchronizedList<>(Bancai.class); public static SynchronizedList<Caizhi> caizhis = new SynchronizedList<>(Caizhi.class); public static SynchronizedList<Mupi> mupis = new SynchronizedList<>(Mupi.class); public static SynchronizedList<Chanpin> chanpins = new SynchronizedList<>(Chanpin.class); public static SynchronizedList<Chanpin_Zujian> chanpinZujians = new SynchronizedList<>(Chanpin_Zujian.class); public static SynchronizedList<Dingdan> dingdans = new SynchronizedList<>(Dingdan.class); public static SynchronizedList<Dingdan_Chanpin> dingdanChanpins = new SynchronizedList<>(Dingdan_Chanpin.class); public static SynchronizedList<Dingdan_chanpin_zujian> dingdanBancais = new SynchronizedList<>(Dingdan_chanpin_zujian.class); public static SynchronizedList<Kucun> kucuns = new SynchronizedList<>(Kucun.class); public static SynchronizedList<Zujian> zujians = new SynchronizedList<>(Zujian.class); public static SynchronizedList<User> users = new SynchronizedList<>(Bancai.class); public static SynchronizedList<Jinhuo> jinhuoList = new SynchronizedList<>(Bancai.class); private static final Gson gson = new Gson(); private static OkHttpClient client ; private static final String TAG = "DataLoader"; public static void loadAllData(Context context, LoadDataCallback callback) { // 确保使用安全的客户端 if (client == null) { client= MyAppFnction.getClient(); } String url = MyAppFnction.getStringResource("string", "url") + MyAppFnction.getStringResource("string", "url_all"); Log.d("url", "loadAllData: " + url); Request request = new Request.Builder() .url(url) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, "Failed to load data", e); if (callback != null) callback.onFailure(); } @Override public void onResponse(Call call, Response response) throws IOException { if (!response.isSuccessful()) { Log.e(TAG, "Unexpected response code: " + response.code()); if (callback != null) callback.onFailure(); return; } String responseData = response.body().string(); parseAndAssignData(responseData, context, callback); } }); } // 解析并赋值数据 private static void parseAndAssignData(String jsonData, Context context, LoadDataCallback callback) { // 创建包含所有数据型的TypeToken Type informationType = new TypeToken<Information<AllDataResponse>>(){}.getType(); Information<AllDataResponse> information = gson.fromJson(jsonData, informationType); Log.e(TAG, "Invalid response data"+jsonData); if (information == null || information.getData() == null || information.getStatus() != 200) { Log.e(TAG, "Invalid response data"); if (callback != null) callback.onFailure(); return; } AllDataResponse allData = information.getData(); // 赋值到对应的列表(使用安全方法保持已有引用) updateList(bancais, allData.bancais); updateList(caizhis, allData.caizhis); updateList(mupis, allData.mupis); updateList(chanpins, allData.chanpins); updateList(chanpinZujians, allData.chanpin_zujians); updateList(dingdans, allData.dingdans); updateList(dingdanChanpins, allData.dingdan_chanpins); updateList(dingdanBancais, allData.dingdan_bancais); updateList(kucuns, allData.kucuns); updateList(zujians, allData.zujians); updateList(users, allData.users); updateList(jinhuoList, allData.jinhuos); resolveReferences(); if (callback != null) callback.onSuccess(); } // 更新列表内容但保持对象引用不变 private static <T> void updateList(List<T> existingList, List<T> newList) { if (newList == null) return; existingList.clear(); existingList.addAll(newList); } // 解析对象间的引用关系(使用ID关联) private static void resolveReferences() { // 创建ID到对象的映射 Map<Integer, Bancai> bancaiMap = createIdMap(bancais); Map<Integer, Caizhi> caizhiMap = createIdMap(caizhis); Map<Integer, Mupi> mupiMap = createIdMap(mupis); Map<Integer, Chanpin> chanpinMap = createIdMap(chanpins); Map<Integer, Zujian> zujianMap = createIdMap(zujians); Map<Integer, Dingdan> dingdanMap = createIdMap(dingdans); Map<Integer, Kucun> kucunMap = createIdMap(kucuns); // 解析Bancai引用 for (Bancai bancai : bancais) { if (bancai.getCaizhi() != null) { bancai.setCaizhi(caizhiMap.get(bancai.getCaizhi().getId())); } if (bancai.getMupi1() != null) { bancai.setMupi1(mupiMap.get(bancai.getMupi1().getId())); } if (bancai.getMupi2() != null) { bancai.setMupi2(mupiMap.get(bancai.getMupi2().getId())); } } // 解析Kucun引用 for (Kucun kucun : kucuns) { if (kucun.getBancai() != null) { kucun.setBancai(bancaiMap.get(kucun.getBancai().getId())); } } // 解析订单相关的嵌套对象 for (Dingdan_Chanpin dc : dingdanChanpins) { if (dc.getDingdan() != null) { dc.setDingdan(dingdanMap.get(dc.getDingdan().getId())); } if (dc.getChanpin() != null) { dc.setChanpin(chanpinMap.get(dc.getChanpin().getId())); } } // 解析产品相关的嵌套对象 for (Chanpin_Zujian cz : chanpinZujians) { if (cz.getChanpin() != null) { cz.setChanpin(chanpinMap.get(cz.getChanpin().getId())); } if (cz.getZujian() != null) { cz.setZujian(zujianMap.get(cz.getZujian().getId())); } if (cz.getBancai() != null) { cz.setBancai(bancaiMap.get(cz.getBancai().getId())); } } // 解析库存关联 for (Kucun k : kucuns) { if (k.getBancai() != null) { k.setBancai(bancaiMap.get(k.getBancai().getId())); } } } // 创建ID到对象的映射 private static <T extends EntityClassGrassrootsid> Map<Integer, T> createIdMap(List<T> list) { Map<Integer, T> map = new HashMap<>(); for (T item : list) { map.put(item.getId(), item); } return map; } // 回调接口 public interface LoadDataCallback { void onSuccess(); void onFailure(); } // 内部用于解析JSON响应 public static class AllDataResponse { public List<Bancai> bancais; public List<Caizhi> caizhis; public List<Mupi> mupis; public List<Chanpin> chanpins; public List<Chanpin_Zujian> chanpin_zujians; public List<Dingdan> dingdans; public List<Dingdan_Chanpin> dingdan_chanpins; public List<Dingdan_chanpin_zujian> dingdan_bancais; public List<Kucun> kucuns; public List<Zujian> zujians; public List<User> users; public List<Jinhuo> jinhuos; } }package com.example.kucun2.entity.data; import android.util.Log; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** 支持数据变更自动同步的泛型集合 基于SynchronizableEntity的事件机制实现数据变更自动同步 @param <T> 必须是SynchronizableEntity或其子 */ public class SynchronizedList<T extends SynchronizableEntity> implements List<T> { // 使用ArrayList作为底层存储 private final List<T> list = new ArrayList<>(); public SynchronizedList(Class T ) { } // 实体变更监听器 private final EntityChangeListener<T> entityChangeListener = new EntityChangeListener<>(); @Override public int size() { return list.size(); } @Override public boolean isEmpty() { return list.isEmpty(); } @Override public boolean contains(Object o) { return list.contains(o); } @Override public Iterator<T> iterator() { return new SyncedIterator<>(list.iterator(), entityChangeListener); } @Override public Object[] toArray() { return list.toArray(); } @Override public <E> E[] toArray(E[] a) { return list.toArray(a); } // 添加元素时注册监听器 @Override public boolean add(T element) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } Log.d(“z”,“element”); return list.add(element); } // 移除元素时注销监听器 @Override public boolean remove(Object o) { if (o instanceof SynchronizableEntity) { ((SynchronizableEntity) o).removePropertyChangeListener(entityChangeListener); } return list.remove(o); } @Override public boolean containsAll(Collection<?> c) { return list.containsAll©; } // 批量添加时逐个注册监听器 @Override public boolean addAll(Collection<? extends T> c) { for (T element : c) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } } return list.addAll©; } @Override public boolean addAll(int index, Collection<? extends T> c) { for (T element : c) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } } return list.addAll(index, c); } // 批量移除时逐个注销监听器 @Override public boolean removeAll(Collection<?> c) { for (Object o : c) { if (o instanceof SynchronizableEntity) { ((SynchronizableEntity) o).removePropertyChangeListener(entityChangeListener); } } return list.removeAll©; } @Override public boolean retainAll(Collection<?> c) { // 先移除未保留元素的监听器 for (T element : list) { if (!c.contains(element)) { element.removePropertyChangeListener(entityChangeListener); } } return list.retainAll©; } // 清空集合时移除所有监听器 @Override public void clear() { for (T element : list) { element.removePropertyChangeListener(entityChangeListener); } list.clear(); } @Override public T get(int index) { return list.get(index); } // 替换元素时更新监听器 @Override public T set(int index, T element) { T oldElement = list.get(index); if (oldElement != null) { oldElement.removePropertyChangeListener(entityChangeListener); } if (element != null) { element.addPropertyChangeListener(entityChangeListener); } return list.set(index, element); } // 在指定位置添加元素时注册监听器 @Override public void add(int index, T element) { if (element != null) { element.addPropertyChangeListener(entityChangeListener); } list.add(index, element); } // 移除元素时注销监听器 @Override public T remove(int index) { T removed = list.remove(index); if (removed != null) { removed.removePropertyChangeListener(entityChangeListener); } return removed; } @Override public int indexOf(Object o) { return list.indexOf(o); } @Override public int lastIndexOf(Object o) { return list.lastIndexOf(o); } @Override public ListIterator<T> listIterator() { return new SyncedListIterator<>(list.listIterator(), entityChangeListener); } @Override public ListIterator<T> listIterator(int index) { return new SyncedListIterator<>(list.listIterator(index), entityChangeListener); } @Override public List<T> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } /** 内部实体变更监听器 监听属性变化并触发同步操作 */ private static class EntityChangeListener<T extends SynchronizableEntity> implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { @SuppressWarnings(“unchecked”) T entity = (T) evt.getSource(); entity.sync(); // 触发同步操作 } } /** 增强的Iterator实现 移除元素时自动注销监听器 */ private static class SyncedIterator<T extends SynchronizableEntity> implements Iterator<T> { private final Iterator<T> iterator; private final EntityChangeListener<T> listener; private T current; public SyncedIterator(Iterator<T> iterator, EntityChangeListener<T> listener) { this.iterator = iterator; this.listener = listener; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { current = iterator.next(); return current; } @Override public void remove() { if (current != null) { current.removePropertyChangeListener(listener); } iterator.remove(); } } /** 增强的ListIterator实现 支持添加/设置元素时的监听器管理 */ private static class SyncedListIterator<T extends SynchronizableEntity> implements ListIterator<T> { private final ListIterator<T> iterator; private final EntityChangeListener<T> listener; private T lastReturned; public SyncedListIterator(ListIterator<T> iterator, EntityChangeListener<T> listener) { this.iterator = iterator; this.listener = listener; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public T next() { lastReturned = iterator.next(); return lastReturned; } @Override public boolean hasPrevious() { return iterator.hasPrevious(); } @Override public T previous() { lastReturned = iterator.previous(); return lastReturned; } @Override public int nextIndex() { return iterator.nextIndex(); } @Override public int previousIndex() { return iterator.previousIndex(); } @Override public void remove() { if (lastReturned != null) { lastReturned.removePropertyChangeListener(listener); } iterator.remove(); } @Override public void set(T e) { if (lastReturned != null) { lastReturned.removePropertyChangeListener(listener); } if (e != null) { e.addPropertyChangeListener(listener); } iterator.set(e); lastReturned = e; } @Override public void add(T e) { if (e != null) { e.addPropertyChangeListener(listener); } iterator.add(e); } } }package com.example.kucun2.entity.data; import android.util.Log; import com.example.kucun2.entity.Information; import com.example.kucun2.function.MyAppFnction; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.HashMap; import java.util.Map; public abstract class SynchronizableEntity implements EntityClassGrassrootsid { public enum SyncState { NEW, MODIFIED, DELETED } SyncState state = SyncState.NEW; // 设置状态的方法 public void setState(SyncState state) { this.state = state; } // 使用标准属性变更支持 private transient PropertyChangeSupport changeSupport = new PropertyChangeSupport(this); // 属性缓存(可选,用于优化) private final Map<String, Object> propertyCache = new HashMap<>(); // 添加属性变更监听器 public void addPropertyChangeListener(PropertyChangeListener listener) { if (changeSupport == null) { changeSupport = new PropertyChangeSupport(this); } changeSupport.addPropertyChangeListener(listener); } // 移除属性变更监听器 public void removePropertyChangeListener(PropertyChangeListener listener) { if (changeSupport != null) { changeSupport.removePropertyChangeListener(listener); } } // 触发属性变更通知(子在setter中调用) protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { if (changeSupport != null && changeSupport.hasListeners(propertyName)) { // 更新属性缓存(可选) propertyCache.put(propertyName, newValue); // 触发变更事件 changeSupport.firePropertyChange(propertyName, oldValue, newValue); } } // 获取属性当前值(可选,用于setter中获取旧值) protected <T> T getCachedProperty(String propertyName) { return (T) propertyCache.get(propertyName); } // 初始化属性缓存(可选,在构造函数中调用) protected void initPropertyCache() { // 初始化所有字段到缓存 for (java.lang.reflect.Field field : getClass().getDeclaredFields()) { try { field.setAccessible(true); propertyCache.put(field.getName(), field.get(this)); } catch (Exception e) { // 忽略初始化异常 } } } /** * 添加url * @param type 操作增删改查 * @return 返回相对url */ public String getEndpoint(String type){ //从String.xml获取url Log.d("getEndpoint", "getEndpoint: "+"url_"+type+"_"+this.getClass().getSimpleName().toLowerCase()); return MyAppFnction.getStringResource("string","url_"+type+"_"+this.getClass().getSimpleName().toLowerCase()); } public void sync() { if (this.state == null) return; try { switch (this.state) { case NEW: createToServer(); break; case MODIFIED: updateToServer(); break; case DELETED: deleteFromServer(); break; } } catch (Exception e) { Log.e("SyncError", "Sync failed for " + getClass().getSimpleName(), e); } } /** * 创建实体到后端 */ private void createToServer() { String endpoint = MyAppFnction.getStringResource("string", "url") + getEndpoint("add"); Information<SynchronizableEntity> requestData = new Information<SynchronizableEntity>(); // 使用Volley、Retrofit或OkHttp执行POST请求 // 伪代码示例: ApiClient.post(endpoint, requestData, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { // 解析服务器返回的ID Log.d("onSuccess",e.toJson()); // String serverId = parseServerId(response); // if (serverId != null) { // // 更新本地ID // setId(serverId); // 需要实体实现setId方法 // } state = SyncState.MODIFIED; } }); } /** * 更新实体到后端 */ private void updateToServer() { String endpoint = MyAppFnction.getStringResource("string", "url") + getEndpoint("update") + "/" + getId(); // 获取实体ID Information<SynchronizableEntity> requestData = new Information<SynchronizableEntity>(); ApiClient.post(endpoint, requestData, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { // 解析服务器返回的ID Log.d("onSuccess",e.toJson()); // String serverId = parseServerId(response); // if (serverId != null) { // // 更新本地ID // setId(serverId); // 需要实体实现setId方法 // } // state = SyncState.MODIFIED; } }); } /** * 从后端删除实体 */ private void deleteFromServer() { String endpoint = MyAppFnction.getStringResource("string", "url") + getEndpoint("delete") + "/" + getId(); ApiClient.delete(endpoint, new ApiClient.ApiCallback<SynchronizableEntity>() { @Override public void onSuccess(Information<SynchronizableEntity> e) { Log.d("SyncDelete", "Successfully deleted " + getId()); } }); } /** * 将实体转换为请求映射 */ protected Information<SynchronizableEntity> toRequestMap(){ return Information.newSuccess(this); } } 初始加载数据时自动同步一直在出发
最新发布
06-12
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值