1. 程式人生 > >android volley封裝及原始碼解析

android volley封裝及原始碼解析

1.簡單使用volley

Volley.newRequestQueue(this).add(new StringRequest(Request.Method.GET, "http://api.wumeijie.net/list", new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        //TODO 處理響應資料
    }
}, new Response.ErrorListener() {
    @Override
    public
void onErrorResponse(VolleyError error) { //TODO 處理請求失敗情況 } }));

2.封裝VolleyManager

注意,volley裡面的請求佇列建議使用單例,因為每次例項化ReqeustQueue並start()時,會建立1個快取執行緒和4個網路請求執行緒,多次呼叫start()會建立多餘的被interrupt的執行緒,造成資源浪費

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import
com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import org.json.JSONObject; import java.util.HashMap; import
java.util.Map; public class VolleyManager { private static RequestQueue requestQueue; //超時時間 30s private final static int TIME_OUT = 30000; private static RequestQueue getRequestQueue() { if (requestQueue == null) { synchronized (VolleyManager.class) { if (requestQueue == null) { //使用全域性context物件 requestQueue = Volley.newRequestQueue(MyApplication.getContext()); } } } return requestQueue; } private static <T> void addRequest(RequestQueue requestQueue, Request<T> request) { request.setShouldCache(true); request.setRetryPolicy(new DefaultRetryPolicy(TIME_OUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT)); requestQueue.add(request); } public static void sendJsonObjectRequest(int method, String url, JSONObject params, final Response.Listener<JSONObject> listener, final Response.ErrorListener errorListener) { try { JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(method, url, params, listener, errorListener) { @Override public Map<String, String> getHeaders() throws AuthFailureError { Map<String, String> headers = new HashMap<>(); headers.put("accept-encoding", "utf-8"); return headers; } }; addRequest(getRequestQueue(), jsonObjectRequest); } catch (Exception e) { e.printStackTrace(); } } public static void sendStringRequest(int method, String url, final Map<String, String> params, final Response.Listener<String> listener, final Response.ErrorListener errorListener) { try { StringRequest stringRequest = new StringRequest(method, url, listener, errorListener) { @Override protected Map<String, String> getParams() throws AuthFailureError { return params; } }; addRequest(getRequestQueue(), stringRequest); } catch (Exception e) { e.printStackTrace(); } } }

封裝完了,使用起來也非常簡單

//使用StringRequest
HashMap<String, String> params = new HashMap<>();
params.put("params1", "xixi");
VolleyManager.sendStringRequest(Request.Method.GET,
        "http://api.wumeijie.net/list", params,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //TODO 處理響應資料
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //TODO 處理請求失敗情況
            }
        });

或者

//使用JsonObjectRequest
JSONObject params = new JSONObject();
try {
    params.put("params1", "xixi");
} catch (JSONException e) {
    e.printStackTrace();
}
VolleyManager.sendJsonObjectRequest(Request.Method.GET,
        "http://api.wumeijie.net/list", params,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                //TODO 處理響應資料
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //TODO 處理請求失敗情況
            }
        });

3.原始碼分析

3.1 Volley在建立RequestQueue時,會先建立一個HttpStack物件,該物件在系統版本>=9時,是由實現類HurlStack建立,具體是用HttpURLConnection來實現網路請求,在系統版本<9時,是由實現類HttpClientStack建立,使用的是HttpClient來實現網路請求
原始碼如下:(Volley類中newRequestQueue方法)

    public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        File cacheDir = new File(context.getCacheDir(), DEFAULT_CACHE_DIR);

        String userAgent = "volley/0";
        try {
            String packageName = context.getPackageName();
            PackageInfo info = context.getPackageManager().getPackageInfo(packageName, 0);
            userAgent = packageName + "/" + info.versionCode;
        } catch (NameNotFoundException e) {
        }

        if (stack == null) {
            if (Build.VERSION.SDK_INT >= 9) {
                stack = new HurlStack();
            } else {
                // Prior to Gingerbread, HttpUrlConnection was unreliable.
                // See: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }

        Network network = new BasicNetwork(stack);

        RequestQueue queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
        queue.start();

        return queue;
    }

3.2 建立RequestQueue,主要是建立了1個快取執行緒和4個網路請求執行緒,這5個執行緒共用1個請求佇列,共用1個快取物件,共用1個ResponseDelivery
原始碼如下:(請求佇列RequestQueue類中start方法)

public void start() {
    stop();  // Make sure any currently running dispatchers are stopped.
    // Create the cache dispatcher and start it.
    mCacheDispatcher = new CacheDispatcher(mCacheQueue, mNetworkQueue, mCache, mDelivery);
    mCacheDispatcher.start();

    // Create network dispatchers (and corresponding threads) up to the pool size.
    for (int i = 0; i < mDispatchers.length; i++) {
        NetworkDispatcher networkDispatcher = new NetworkDispatcher(mNetworkQueue, mNetwork,
                mCache, mDelivery);
        mDispatchers[i] = networkDispatcher;
        networkDispatcher.start();
    }
}

3.3 快取執行緒run方法中,主要是一個死迴圈,不斷的從快取佇列中取出請求物件,如果該請求物件快取丟失或者不需要快取或者需要重新整理快取資料,則加入到請求佇列中,否則,直接解析快取後通過ResponseDelivery物件中的handler post到主執行緒中執行響應回撥介面
原始碼如下:(快取執行緒CacheDispatcher類中run方法)

@Override
public void run() {
    if (DEBUG) VolleyLog.v("start new dispatcher");
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);

    // Make a blocking call to initialize the cache.
    mCache.initialize();

    while (true) {
        try {
            // Get a request from the cache triage queue, blocking until
            // at least one is available.
            final Request<?> request = mCacheQueue.take();
            request.addMarker("cache-queue-take");

            // If the request has been canceled, don't bother dispatching it.
            if (request.isCanceled()) {
                request.finish("cache-discard-canceled");
                continue;
            }

            // Attempt to retrieve this item from cache.
            Cache.Entry entry = mCache.get(request.getCacheKey());
            if (entry == null) {
                request.addMarker("cache-miss");
                // Cache miss; send off to the network dispatcher.
                mNetworkQueue.put(request);
                continue;
            }

            // If it is completely expired, just send it to the network.
            if (entry.isExpired()) {
                request.addMarker("cache-hit-expired");
                request.setCacheEntry(entry);
                mNetworkQueue.put(request);
                continue;
            }

            // We have a cache hit; parse its data for delivery back to the request.
            request.addMarker("cache-hit");
            Response<?> response = request.parseNetworkResponse(
                    new NetworkResponse(entry.data, entry.responseHeaders));
            request.addMarker("cache-hit-parsed");

            if (!entry.refreshNeeded()) {
                // Completely unexpired cache hit. Just deliver the response.
                mDelivery.postResponse(request, response);
            } else {
                // Soft-expired cache hit. We can deliver the cached response,
                // but we need to also send the request to the network for
                // refreshing.
                request.addMarker("cache-hit-refresh-needed");
                request.setCacheEntry(entry);

                // Mark the response as intermediate.
                response.intermediate = true;

                // Post the intermediate response back to the user and have
                // the delivery then forward the request along to the network.
                mDelivery.postResponse(request, response, new Runnable() {
                    @Override
                    public void run() {
                        try {
                            mNetworkQueue.put(request);
                        } catch (InterruptedException e) {
                            // Not much we can do about this.
                        }
                    }
                });
            }

        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }
    }
}

3.4 網路執行緒run方法中,主要是一個死迴圈,不斷的從請求佇列中取出請求物件,然後根據系統版本使用HttpStack物件來進行網路請求(包括設定請求引數,請求頭,請求方法等資訊),最終返回一個HttpResponse物件,接著就是解析響應資料,處理快取情況,最後通過ResponseDelivery物件中的handler post到主執行緒中執行響應回撥介面
原始碼如下:(網路請求執行緒NetWorkDispatcher類中run方法)

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    while (true) {
        long startTimeMs = SystemClock.elapsedRealtime();
        Request<?> request;
        try {
            // Take a request from the queue.
            request = mQueue.take();
        } catch (InterruptedException e) {
            // We may have been interrupted because it was time to quit.
            if (mQuit) {
                return;
            }
            continue;
        }

        try {
            request.addMarker("network-queue-take");

            // If the request was cancelled already, do not perform the
            // network request.
            if (request.isCanceled()) {
                request.finish("network-discard-cancelled");
                continue;
            }

            addTrafficStatsTag(request);

            // Perform the network request.
            NetworkResponse networkResponse = mNetwork.performRequest(request);
            request.addMarker("network-http-complete");

            // If the server returned 304 AND we delivered a response already,
            // we're done -- don't deliver a second identical response.
            if (networkResponse.notModified && request.hasHadResponseDelivered()) {
                request.finish("not-modified");
                continue;
            }

            // Parse the response here on the worker thread.
            Response<?> response = request.parseNetworkResponse(networkResponse);
            request.addMarker("network-parse-complete");

            // Write to cache if applicable.
            // TODO: Only update cache metadata instead of entire record for 304s.
            if (request.shouldCache() && response.cacheEntry != null) {
                mCache.put(request.getCacheKey(), response.cacheEntry);
                request.addMarker("network-cache-written");
            }

            // Post the response back.
            request.markDelivered();
            mDelivery.postResponse(request, response);
        } catch (VolleyError volleyError) {
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            parseAndDeliverNetworkError(request, volleyError);
        } catch (Exception e) {
            VolleyLog.e(e, "Unhandled exception %s", e.toString());
            VolleyError volleyError = new VolleyError(e);
            volleyError.setNetworkTimeMs(SystemClock.elapsedRealtime() - startTimeMs);
            mDelivery.postError(request, volleyError);
        }
    }
}

3.5 當步驟3.4中執行

NetworkResponse networkResponse = mNetwork.performRequest(request);

時,會將請求分發給不同版本的網路請求實現類,這裡以HurlStack為例,請求最終分發到HurlStack中的performRequest方法執行
原始碼如下:(HurlStack類中performRequest方法)

@Override
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws IOException, AuthFailureError {
    String url = request.getUrl();
    HashMap<String, String> map = new HashMap<String, String>();
    map.putAll(request.getHeaders());
    map.putAll(additionalHeaders);
    if (mUrlRewriter != null) {
        String rewritten = mUrlRewriter.rewriteUrl(url);
        if (rewritten == null) {
            throw new IOException("URL blocked by rewriter: " + url);
        }
        url = rewritten;
    }
    URL parsedUrl = new URL(url);
    HttpURLConnection connection = openConnection(parsedUrl, request);
    for (String headerName : map.keySet()) {
        connection.addRequestProperty(headerName, map.get(headerName));
    }
    setConnectionParametersForRequest(connection, request);
    // Initialize HttpResponse with data from the HttpURLConnection.
    ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
    int responseCode = connection.getResponseCode();
    if (responseCode == -1) {
        // -1 is returned by getResponseCode() if the response code could not be retrieved.
        // Signal to the caller that something was wrong with the connection.
        throw new IOException("Could not retrieve response code from HttpUrlConnection.");
    }
    StatusLine responseStatus = new BasicStatusLine(protocolVersion,
            connection.getResponseCode(), connection.getResponseMessage());
    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromConnection(connection));
    for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
        if (header.getKey() != null) {
            Header h = new BasicHeader(header.getKey(), header.getValue().get(0));
            response.addHeader(h);
        }
    }
    return response;
}

3.6 執行完步驟3.5後,拿到一個響應物件HttpResponse,接著步驟3.4解析響應物件:

Response<?> response = request.parseNetworkResponse(networkResponse);

,執行響應回撥:

mDelivery.postResponse(request, response);

這個mDelivery(ExecutorDelivery型別)就是在建立RequestQueue時建立的ResponseDelivery物件,主要負責回撥響應介面
注:ExecutorDelivery implements ResponseDelivery
原始碼如下:(ExecutorDelivery類中postResponse方法)

@Override
public void postResponse(Request<?> request, Response<?> response, Runnable runnable) {
    request.markDelivered();
    request.addMarker("post-response");
    mResponsePoster.execute(new ResponseDeliveryRunnable(request, response, runnable));
}

ExecutorDelivery屬性mResponsePoster具體實現有兩種方式,這裡使用的是handler實現
原始碼如下:(ExecutorDelivery類的構造方法)

public ExecutorDelivery(final Handler handler) {
    // Make an Executor that just wraps the handler.
    mResponsePoster = new Executor() {
        @Override
        public void execute(Runnable command) {
            handler.post(command);
        }
    };
}

注:這個構造方法傳進來的Handler物件拿的是主執行緒中的Looper物件