先看volley这个类 volley有四种构造方法
四种构造方法实质都是调用的第一个。只不过写一个参数的时候其他参数为默认的值。
public static RequestQueue newRequestQueue(Context context) {
return newRequestQueue(context, null);
}
第一个就是传进去一个context上下文对象,主要用于获取缓存。the context to use for creating the cache dir
看代码知道这个是调用了两个参数的构造方法,而两个参数构造方法源码如下
public static RequestQueue newRequestQueue(Context context, HttpStack stack)
{
return newRequestQueue(context, stack, -1);
}
HttpStack是一个接口 实现此接口的为封装的HttpUrlConnection或者HttpClient方法,
public interface HttpStack {
public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError;
}
执行performRequest方法连接网络返回一个httpResponse对象。其中Request是封装的request请求,这里暂且不看。先回到volley类。
volley构造方法参数为两个的还有一个方法即下面这个
public static RequestQueue newRequestQueue(Context context, int maxDiskCacheBytes) {
return newRequestQueue(context, null, maxDiskCacheBytes);
}
其中context还是作为缓存使用,而maxDiskCacheBytes即设置缓存大小 传-1时为默认缓存大小:5M。后面会有源码实现。这里就不贴了。
最后看真正volley的构造方法
private static final String DEFAULT_CACHE_DIR = "volley"
public static RequestQueue newRequestQueue(Context context, HttpStack stack, int maxDiskCacheBytes) {
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;
if (maxDiskCacheBytes <= -1)
{
// No maximum size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir), network);
}
else
{
// Disk cache size specified
queue = new RequestQueue(new DiskBasedCache(cacheDir, maxDiskCacheBytes), network);
}
queue.start();
return queue;
}
首先在 程序包下面建了一个缓存目录 文件路径wei com.xxx /caches/volley
然后将http请求中的user-agent设置为 包名+版本号 例如 com.xxx/46
在2.3以上,默认使用HttpUrlConnection 而2.3一下用 HttpClient
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));
}
}
最后新建了一个RequestQueue 队列存储网络请求。
下面要读BasicNetwork类和RequestQueue类