Okhttp和Volley

Okhttp和Volley

一、Okhttp

okhttp是一个第三方类库,用于android中请求网络。
这是一个开源项目,是安卓端最火热的轻量级框架,由移动支付Square公司贡献(该公司还贡献了Picasso和LeakCanary) 。用于替代HttpUrlConnection和Apache HttpClient(android API23 里已移除HttpClient)。

  1. 同步get请求:开启子线程`
 public static String okHttp_get(String urlStr){
        String result = null;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);
        builder.readTimeout(2,TimeUnit.MINUTES);

        OkHttpClient client = new OkHttpClient();//客户端

        Request request = new Request.Builder().url(urlStr).get().build();
        try {
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                result = response.body().string();
            }else{
                Log.e("###","失败");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
  1. 同步post请求:开启子线程
public static String okHttp_post(String urlStr){
        String result = null;
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);
        builder.readTimeout(2,TimeUnit.MINUTES);

        OkHttpClient client = new OkHttpClient();//客户端
        FormBody body = new FormBody.Builder()
                .add("phone","17600682866")
                .add("passwd","1234")
                .build();
        Request request = new Request.Builder().url(urlStr).post(body).build();
        try {
            Response response = client.newCall(request).execute();
            if(response.isSuccessful()){
                result = response.body().string();
            }else{
                Log.e("###","失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
  1. 异步get请求:不需要开启子线程
public static void async_get(String urlStr){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);
        builder.readTimeout(2,TimeUnit.MINUTES);

        OkHttpClient client = new OkHttpClient();//客户端
        final Request request = new Request.Builder().url(urlStr).get().build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                Log.e("###",result);
            }
        });

    }
  1. 异步post请求:不需要开启子线程
public static void async_post(String urlStr){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);
        builder.readTimeout(2,TimeUnit.MINUTES);

        OkHttpClient client = new OkHttpClient();//客户端
        FormBody body = new FormBody.Builder()
                .add("phone","11111111111")
                .add("passwd","12345")
                .build();
        Request request = new Request.Builder().url(urlStr).post(body).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String string = response.body().string();
                Log.e("###",string);
            }
        });

    }

二、Volley

  • 所谓Volley,它是2013年Google I/O上发布的一款网络框架,基于Android平台,能使网络通信更快,更简单,更健全
  • 优点:
    (1)默认Android2.3及以上基于HttpURLConnection,2.3以下使用基于HttpClient;
    (2)符合Http 缓存语义 的缓存机制(提供了默认的磁盘和内存等缓存);
    (3)请求队列的优先级排序;
    (4)提供多样的取消机制;
    (5)提供简便的图片加载工具(其实图片的加载才是我们最为看重的功能);(6)一个优秀的框架。
  • 缺点:
    它只适合数据量小,通信频繁的网络操作,如果是数据量大的,像音频,视频等的传输,还是不要使用Volley的为好
  • 工作原理
    在这里插入图片描述
    其中蓝色的是主线程,绿色的是缓存线程,黄色的是网络线程

1.当一个Request请求添加到RequestQueue请求队列中,Volley就开始工作了。RequestQueue请求队列中持有一个CacheDispatcher缓存管家和一组NetworkDispatcher网络管家。

2.RequestQueue会先叫来CacheDispatcher缓存管家,让他去看看,当前请求的数据在没在cache中。

2.1.当前的数据在cache中,那就把数据从cache中取出来,然后经过一番加工,将加工好的数据交付给主线程

2.2.当前数据没在cache中,进行第3步

3.进行到了这一步,那肯定是数据没有在缓存中,那只能去网络中获取了,这时候RequestQueue会叫来NetworkDispatcher,NetworkDispatcher可是有一帮呢,其实这是一个线程池,默认情况下会启动4个线程去网络下载数据。所以RequestQueue把当前闲着的NetworkDispatcher叫来,给他们分配任务。
4.拿到任务的NetworkDispatcher就会去网络上下载数据了,与此同时,他会判断下载到的数据能否写入到cache缓存中,如果可以的话就写入cache,以便于下一次直接从cache中获取到数据。最后,将数据加工,交付给主线程。

  1. get请求
public static void volleyGet(String urlStr, Context context){
        RequestQueue queue = Volley.newRequestQueue(context);//获取volley队列
        StringRequest request = new StringRequest(StringRequest.Method.GET,urlStr,listener,errorListener);
        queue.add(request);//将请求添加到队列
        queue.start();//启动队列
    }
        static com.android.volley.Response.Listener<String> listener = new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("###",response);
        }
    };

    static com.android.volley.Response.ErrorListener errorListener = new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };
  1. post请求
public static void volleyPost(String urlStr, Context context){
        RequestQueue queue = Volley.newRequestQueue(context);//获取volley队列
        StringRequest request = new StringRequest(StringRequest.Method.POST,urlStr,listener,errorListener){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> map = new HashMap<>();
                map.put("phone","12222222222222222");
                map.put("passwd","123456789");
                return map;
            }
        };
        queue.add(request);//将请求添加到队列
        queue.start();//启动队列
    }
        static com.android.volley.Response.Listener<String> listener = new com.android.volley.Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Log.e("###",response);
        }
    };

    static com.android.volley.Response.ErrorListener errorListener = new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };
  1. 请求图片
public static void volleyImage(String urlStr, Context context,final ImageView showImg){
        RequestQueue queue = Volley.newRequestQueue(context);
        ImageRequest request = new ImageRequest(urlStr, new com.android.volley.Response.Listener<Bitmap>() {
            @Override
            public void onResponse(Bitmap response) {
                showImg.setImageBitmap(response);
            }
        }, 400, 400, Bitmap.Config.ARGB_8888,errorListener);
        queue.add(request);
        queue.start();
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值