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

完整代码:https://github.com/snailycy/volley_manager

注意,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对象

volley源码:https://android.googlesource.com/platform/frameworks/volley


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com 联系我们: