OkHttp3 框架学习

1.Okhttp介绍

android网络框架Okhttp,是轻量级框架,由移动支付Square公司贡献
优点:
允许连接到同一个主机地址的所有请求,提高请求效率
共享Socket,减少对服务器的请求次数
通过连接池,减少了请求延迟
缓存响应数据来减少重复的网络请求
减少了对数据流量的消耗
自动处理GZip压缩
功能:
get,post请求
文件的上传下载
加载图片
支持请求回调,直接返回对象、对象集合
支持session的保持

2.开源项目地址

https://github.com/square/okhttp
下载
# git clone https://github.com/square/okhttp.git
在build.gradle(Module:app)中增加
dependencies {
 implementation 'com.squareup.okhttp3:okhttp:3.9.1'
}

3.核心类

1)OkHttpClient创建OkHttpCLient对象
OkHttpClient client = new OkHttpClient();
2)Request
构造一个Request对象
通过Request.BUilder()设置参数,默认的是get请求
Request request = new Request.Builder()
                        .url(url)
                        .build();
3)通过request对象去构造一个Call对象,将请求封装成了任务
用call.enqueue异步去执行请求,将call加入调度队列,在Callback中即可得到结果
client.newCall(request).enqueue(new Callback()

请求网络的时候我们需要用OkHttpClient.newCall(request)进行execute或者enqueue操作

4)回调结果onResponse
@Override
public void onResponse(Call call, Response response) throws IOException {
                       final String str = response.networkResponse().toString();
                        
});
onResponse回调的参数是response,一般情况下,比如我们希望获得返回的字符串,可以通过
response.body().string()获取;如果希望获得返回的二进制字节数组,则调用
response.body().bytes();如果你想拿到返回的inputStream,则调用
response.body().byteStream()
5)post请求传参时构造RequestBody
 RequestBody fromBody = new FormBody.Builder()
                        .add("key","8db57b752c2b47599348865ccfd30ba4")
                        .add("location","成都")
                        .build();
post(fromBody);

能过POST方式把键值对数据传送到服务器,post提交键值对比get方法多了一个RequestBody
//提交Json数据
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    
    
     OkHttpClient client = new OkHttpClient();
     RequestBody body = RequestBody.create(JSON, json);
     Request request = new Request.Builder()
      .url(url)
      .post(body)
      .build();

------------------------------------------------------------------------------------------------------

4.Demo

public class MainActivity extends AppCompatActivity {
    private Button btGet;
    private Button btPost;
    private Button btFileDownload;
    private Button btUpload;
    private Button btPicture;
    private ImageView iv;

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btGet = (Button)findViewById(R.id.btGet);
        btPost = (Button)findViewById(R.id.btPost);
        btFileDownload = (Button)findViewById(R.id.btFileDownload);
        btUpload = (Button)findViewById(R.id.btUpload);
        btPicture = (Button)findViewById(R.id.btPicture);
        iv = (ImageView)findViewById(R.id.imageView);

        tv = (TextView)findViewById(R.id.textView);

        //异步Get
        btGet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="https://www.baidu.com";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();

                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                       //请求网页的内容
                        final String str = response.body().string();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText(str);
                            }
                        });
                    }
                });
            }
        });

        //异步POST请求
        //注册一个和风的账号https://www.heweather.com/
        //可以获取一个key,根据key,和location可以查询weather
        btPost.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="https://free-api.heweather.com/s6/weather";
                OkHttpClient client = new OkHttpClient();
                RequestBody fromBody = new FormBody.Builder()
                        .add("key","8db57b752c2b47599348865ccfd30ba4")
                        .add("location","成都")
                        .build();
                Request request = new Request.Builder()
                        .url(url)
                        .post(fromBody)
                        .build();

                client.newCall(request)
                        .enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {
                                Log.i("tag","post fail");
                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                final String str = response.body().string();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        tv.setText(str);
                                    }
                                });
                            }
                        });
            }
        });
        //异步文件下载
        //下载一张图片,将流写进指定的图片文件中
        btFileDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="http://192.168.42.218:8080/flower.jpeg";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request
                        .Builder()
                        .url(url)
                        .build();
                client.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                tv.setText("文件下载失败");
                            }
                        });

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //把请求成功的response转为字节流
                        InputStream inputStream = response.body().byteStream();
                        FileOutputStream fileOutputStream = null;
                        try{
                            fileOutputStream = new FileOutputStream(
                                    new File("/mnt/sdcard/test.jpeg"));
                            byte[] buffer = new byte[2048];
                            int len = 0;
                            while((len=inputStream.read(buffer))!= -1){
                                fileOutputStream.write(buffer,0,len);
                            }
                            fileOutputStream.flush();
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv.setText("文件下载成功");
                                }
                            });

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

                    }
                });
            }
        });
        //异步上传文件
        btUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url ="http://192.168.42.218:8080/";
                File file = new File("/mnt/sdcard/wifi");
                OkHttpClient client = new OkHttpClient();
                Request request = new Request
                        .Builder()
                        .url(url)
                        .post(RequestBody.create(MediaType.parse("application/octet-stream"), file))
                        .build();
                client.newCall(request)
                        .enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, final Response response) throws IOException {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv.setText("上传成功:"+response.body().toString());
                                }
                            });
                            }
                        });
            }
        });
        //图片下载并显示到imageView中
        btPicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "http://192.168.42.218:8080/flower.jpeg";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request
                        .Builder()
                        .url(url)
                        .build();
                client.newCall(request)
                        .enqueue(new Callback() {
                            @Override
                            public void onFailure(Call call, IOException e) {

                            }

                            @Override
                            public void onResponse(Call call, Response response) throws IOException {
                                //获取流
                                InputStream in = response.body().byteStream();
                                //转化为bitmap
                                final Bitmap bitmap = BitmapFactory.decodeStream(in);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        iv.setImageBitmap(bitmap);
                                    }
                                });
                            }
                        });
            }
        });
    }
}
参考: http://www.heweather.com/ http://blog.csdn.net/lmj623565791/article/details/47911083 http://blog.csdn.net/itachi85/article/details/51190687
相关文章
相关标签/搜索
每日一句
    每一个你不满意的现在,都有一个你没有努力的曾经。
公众号推荐
   一个健康类的公众号,欢迎关注
小青桔健康