OkHttp以及Volley简答介绍以及使用

Android

    • OkHttp
    • Volley

OkHttp

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

1.同步get请求:开启子线程
2.同步post请求:开启子线程
3.异步get请求:不需要开启子线程
4.异步post请求:不需要开启子线程

Volley

所谓Volley,它是2013年Google I/O上发布的一款网络框架,基于Android平台,能使网络通信更快,更简单,更健全

优点:
(1)默认Android2.3及以上基于HttpURLConnection,2.3以下使用基于HttpClient;
(2)符合Http 缓存语义 的缓存机制(提供了默认的磁盘和内存等缓存);
(3)请求队列的优先级排序;
(4)提供多样的取消机制;
(5)提供简便的图片加载工具(其实图片的加载才是我们最为看重的功能);(6)一个优秀的框架。

缺点:
它只适合数据量小,通信频繁的网络操作,如果是数据量大的,像音频,视频等的传输,还是不要使用Volley的为好

工作原理

OkHttp以及Volley简答介绍以及使用_第1张图片

其中蓝色的是主线程,绿色的是缓存线程,黄色的是网络线程

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中获取到数据。最后,将数据加工,交付给主线程。

package com.example.posthhttpurl;

import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    ImageView imageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView=findViewById(R.id.image);
        //http://10.211.55.6:8080/lianxi/login

        //同步get的
//        new MythreadPost("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&").start();
//        new MyOkHttpThread().start();//同步post的
//        ayncGet();//异步get的
//        asyncPost();//异步post的

//       Bolleyget();//Volleyget的
//        volleypost();//Volleypost的
       volleyImage();//图片的
    }


    class MythreadPost extends Thread {

        String ss;

        public MythreadPost(String ss) {
            this.ss = ss;
        }

        @Override
        public void run() {
            super.run();
            try {
                URL url = new URL(ss);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setReadTimeout(200);
                connection.setConnectTimeout(200);

                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setUseCaches(false);

                OutputStream outputStream = connection.getOutputStream();

                String parm = "page";
                String vlaue = "2";
                outputStream.write("page=2".getBytes());
//                outputStream.flush();
                outputStream.close();
                Log.d("3######", ss);

                if (connection.getResponseCode() == 200) {
                    byte[] bytes = new byte[1024];
                    int len = 0;
                    StringBuilder builder = new StringBuilder();
                    InputStream inputStream = connection.getInputStream();
                    while ((len = inputStream.read(bytes)) != -1) {
                        String s = new String(bytes, 0, len);
                        builder.append(s);
                    }
                    Log.d("3######", builder.toString());
                }


            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    class MyOkHttpThread extends Thread {

        @RequiresApi(api = Build.VERSION_CODES.N)
        @Override
        public void run() {
            super.run();
//            mYokHttp();
            OkHTTP_post();
        }
    }

    /**
     * OKHttp 同步的方式获取网络数据
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void mYokHttp() {

//        OkHttpClient.Builder builder = new OkHttpClient.Builder();
//        builder.connectTimeout(20000, TimeUnit.MILLISECONDS);//设置链接超时
//        builder.readTimeout(4,TimeUnit.MINUTES);//分钟
//        OkHttpClient client=builder.build();//客户端
//
////        Request.Builder builder1=new Request.Builder();
////        builder1.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&");//访问网址
////        Request request=builder1.build();
//
       Request request1=new Request.Builder().url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&").get().build();
       Call call=client.newCall(request1);

      try {
           Response execute = call.execute();
           String s = execute.body().string();//拿到Json串
            Log.d("3######", s);
       } catch (IOException e) {
           e.printStackTrace();
        }

        Request request = new Request.Builder().url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&").get().build();

        OkHttpClient client1 = new OkHttpClient();

        try {
            Response response = client1.newCall(request).execute();

            if (response.isSuccessful()) {
                String json = response.body().string();
                Log.d("#####", json);
            } else {
                Log.d("#####", "失败");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    /**
     * 同步的Post方式
     */
    public void OkHTTP_post() {


//        Request.Builder  rebuilder=new Request.Builder();
//
//        rebuilder.url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&");
//        FormBody.Builder builder=new FormBody.Builder();
//        builder.add("phone","156416518613");
//        builder.add("passwd","00000");
//        FormBody build = builder.build();
//        rebuilder.post(build);
//
//
//      Request request=rebuilder.build();

 //      OkHttpClient.Builder builder1=new OkHttpClient.Builder();
  //    OkHttpClient build1 = builder1.build();
//Call call = build1.newCall(request);
//        try {
//            String string = call.execute().body().string();
//            Log.d("#####", string);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }


        RequestBody body = new FormBody.Builder().add("phone", "sdf")
                .add("passwd", "123").build();

        Request request = new Request.Builder().url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&")
                .post(body).build();
        OkHttpClient client = new OkHttpClient();

        try {
            Response execute = client.newCall(request).execute();
            if (execute.isSuccessful()) {
                String string = execute.body().string();
                Log.d("#####", string);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 异步getOkhttp
     */
    public void ayncGet() {
        //获得请求对象
        Request request = new Request.Builder().url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&").get().build();
        //获取客户端对象
        OkHttpClient client = new OkHttpClient();
        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.d("#####", string);

            }
        });
    }

    public void asyncPost() {
        OkHttpClient okHttpClient = new OkHttpClient();
        FormBody body = new FormBody.Builder()
                .add("phone", "qqeasd")
                .add("passwd", "123")
                .build();


        Request request = new Request.Builder().url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&").post(body).build();

        Call call = okHttpClient.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.d("#####", string);

            }
        });
    }

    //VolleyGet
    public void Bolleyget() {
        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request = new StringRequest(StringRequest.Method.GET, "http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&", listener, errlistener);

        queue.add(request);//将请求添加到队列
        queue.start();//启动队列
    }
        //VolleyPost
    public void volleypost(){

        RequestQueue queue = Volley.newRequestQueue(this);
        StringRequest request=new StringRequest(StringRequest.Method.POST,"https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&", listener, errlistener){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String,String> map=new HashMap<>();
                map.put("phone","yzh");
                map.put("passwd","yzh");
                return map;

            }
        };
        queue.add(request);
        queue.start();
    }
       //VolleyImage
    public void volleyImage(){
        RequestQueue queue = Volley.newRequestQueue(this);

        ImageRequest request=new ImageRequest("http://e0.ifengimg.com/07/2019/0203/7909002DC8B62C351C154574DE1C071F2B30AE62_size15_w580_h326.jpeg",imager,500,500, Bitmap.Config.RGB_565,errlistener);
        queue.add(request);
        queue.start();
    }
    com.android.volley.Response.Listener imager = new com.android.volley.Response.Listener<Bitmap>() {

        @Override
        public void onResponse(Bitmap response) {
            imageView.setImageBitmap(response);
        }
    };
    com.android.volley.Response.Listener listener = new com.android.volley.Response.Listener<String>() {

        @Override
        public void onResponse(String response) {

            Log.d("#####", response);

        }
    };
    com.android.volley.Response.ErrorListener errlistener = new com.android.volley.Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {

        }
    };
}

你可能感兴趣的:(简单控件方法的使用与了解)