Volley

1、Volley的简单使用:
首先创建requestQueue请求队列:
RequestQueue requestQueue = Volley.newRequestQueue(context);
接着创建请求,这里以StringRequest为例:

StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener() {
    @Override
    public void onResponse(String response) {
     //这里可以更新UI
    }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {

    }
});

最后到request加入到队列中:

requestQueue.add(stringRequest);

2、源码分析:
首先从创建队列的方法开始分析:

public static RequestQueue newRequestQueue(Context context, HttpStack stack) {
        //创建缓存文件
        File cacheDir = new File(context.getCacheDir(), "volley");
        String userAgent = "volley/0";

        try {
            String network = context.getPackageName();
            PackageInfo queue = context.getPackageManager().getPackageInfo(network, 0);
            userAgent = network + "/" + queue.versionCode;
        } catch (NameNotFoundException var6) {
            ;
        }

        if(stack == null) {
            if(VERSION.SDK_INT >= 9) {
                //9以上系统使用HttpUrlConnection发送请求
                stack = new HurlStack();
            } else {
               //9以下使用HttpClient发送
                stack = new HttpClientStack(AndroidHttpClient.newInstance(userAgent));
            }
        }
        //发送网络请求
        BasicNetwork network1 = new BasicNetwork((HttpStack)stack);
        RequestQueue queue1 = new RequestQueue(new DiskBasedCache(cacheDir), network1);
        queue1.start();
        return queue1;
    }

你可能感兴趣的:(Volley)