OkHttp3

使用方法

1.创建OkHttpClient对象

  • 使用OkHttp的内部类Builder进行客户端的参数配置
		File sdcache = getExternalCacheDir();
        int cacheSize = 10 * 1024 * 1024;  //缓存有关参数
        //使用内部类Builder进行OKHttpClient对象的参数配置,一般不直接进行new OKHttpClient,而是用Builder.builder返回
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .connectTimeout(15, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)			//设置超时时间
                .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize));
        mOkHttpClient = builder.build();    //build()方法会返回一个OkHttp对象
  • 直接使用new构建默认参数的对象

2.创建Request对象

与OkHttp对象创建类似,需要一个内部类Builder的实例进行参数配置

 Request.Builder requestBuilder = new Request.Builder()
 							.url("http://www.baidu.com")
  							.method("GET", null);   //Builder()无参构造函数默认GET方法
 		 Request request = requestBuilder.build();

3.通过OKHttpClient对象的newCall方法进行创建Call对象

其中request对象作为newCall的参数

Call mcall = mOkHttpClient.newCall(request);

4.发起请求

  • 同步请求(立即访问立即得到响应)
mcall.execute();
  • 异步请求(访问之后需要排队、得到的响应通过接口回调的方式进行返回)
mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {		//访问失败的逻辑
            
                        }
            @Override
            public void onResponse(Call call, Response response) throws IOException {		//访问成功的逻辑
            	//响应的数据是String
                String str = response.body().string();
                //响应的数据是文件 
                InputStream in = response.body().byteStream();               
                //响应的数据是图片
                byte[] image = response.body().bytes();
                
                runOnUiThread(new Runnable() {		//更新UI
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(), "请求成功", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

5.请求类型

GET
  • 创建Request对象的时候设置方法method(“GET”),默认是GET,因此可以省略
  • 获取网页资源,直接放URL就行
  • 下载文件(有输入和输出操作)
//在onResponse中实现
InputStream inputStream = response.body().byteStream();	//搭建网络和内存的桥梁
                FileOutputStream fileOutputStream = null;
                String filepath = "";
                try {		//获取文件路径
                    if (Environment.getExternalStorageState().equals(
                            Environment.MEDIA_MOUNTED)) {
                        filepath = Environment.getExternalStorageDirectory().getAbsolutePath();
                    } else {
                        filepath = getFilesDir().getAbsolutePath();
                    }
                    File file = new File(filepath, "wangshu.jpg");
                    if (null != file) {
                        fileOutputStream = new FileOutputStream(file);		//搭建内存和磁盘的桥梁
                       //读取开始
                        byte[] buffer = new byte[2048];//缓冲区
                        int len = 0;
                        while ((len = inputStream.read(buffer)) != -1) {
                            fileOutputStream.write(buffer, 0, len);
                        }
                        fileOutputStream.flush();//将缓冲的数据全部推出去
POST
  • 需要RequestBody对象进行参数的封装
//示例:请求淘宝响应IP的资源
RequestBody formBody = new FormBody.Builder()
                .add("ip", "59.108.54.37")
                .build();
        Request request = new Request.Builder()
                .url("http://ip.taobao.com/service/getIpInfo.php")
                .post(formBody)
                .build();
  • 上传文件也属于POST请求,操作类似

6.取消请求

调用Call对象的cancel方法进行取消请求

private ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);		//该线程池用于处理定时任务
		executor.schedule(new Runnable() {
            @Override
            public void run() {
                finalCall.cancel();
            }
        }, 1, TimeUnit.MILLISECONDS);		//1毫秒之后取消访问

源码理解

请求流程图
在这里插入图片描述

异步请求

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值