Day3:okhttp

一. okhttp协议介绍

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

二.okhttp完成get请求

添加依赖:
implementation ‘com.squareup.okhttp3:okhttp:3.12.1’//okhttp依赖

//网络请求json串
    public void getjson(){
        //TODO 1:client
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.callTimeout(5, TimeUnit.SECONDS);//连接超时
        builder.readTimeout(5,TimeUnit.SECONDS);//读取超时
        OkHttpClient client = builder.build();
        //TODO 2:request对象
        Request.Builder builder1 = new Request.Builder();
        builder1.url("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=20&");//设置网址
        builder1.get();//设置请求方法
        Request request = builder1.build();
        //TODO 3:发起连接call
        Call call = client.newCall(request);
        //TODO 4:通过call得到response
        call.enqueue(new Callback() {
            //请求失败
            @Override
            public void onFailure(Call call, IOException e) {
            }
            //请求成功
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获得响应体:json串
                ResponseBody body = response.body();
                //通过body直接转成字符串
                String json = body.string();
               // Toast.makeText(MainActivity.this, ""+json, Toast.LENGTH_SHORT).show();
                Message obtain = Message.obtain();
                obtain.what=GET_JSON_OK;
                obtain.obj=json;
                handler.sendMessage(obtain);

            }
        });
    }

三-1.okhttp完成post请求

//post请求完成注册
    private void zhuce() {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        //请求体:phone=13594347817&passwd=123654
        FormBody formBody = new FormBody.Builder()
                .add("phone", "13594343356")
                .add("passwd", "123654")
                .build();
        final Request request = new Request.Builder()
                .url("https://www.apiopen.top/createUser?key=00d91e8e0cca2b76f515926a36db68f5&")
                .post(formBody)//post提交必须要设置请求体
                .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();
                Message obtain = Message.obtain();
                obtain.what=GET_JSON_OK;
                obtain.obj=string;
                handler.sendMessage(obtain);
            }
        });
    }

三-2.okhttp完成post请求(参数为json格式)

//post请求完成注册
   OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(60000, TimeUnit.SECONDS)
                .writeTimeout(60000, TimeUnit.SECONDS)
                .readTimeout(60000, TimeUnit.SECONDS)
                .build();
        //请求体 json串 自己拼接
        String json="{\n" +
                "\t\"reqType\":0,\n" +
                "    \"perception\": {\n" +
                "        \"inputText\": {\n" +
                "            \"text\": \"附近的酒店\"\n" +
                "        },\n" +
                "        \"inputImage\": {\n" +
                "            \"url\": \"0292580832850.jpg\"\n" +
                "        },\n" +
                "        \"selfInfo\": {\n" +
                "            \"location\": {\n" +
                "                \"city\": \"北京\",\n" +
                "                \"province\": \"北京\",\n" +
                "                \"street\": \"信息路\"\n" +
                "            }\n" +
                "        }\n" +
                "    },\n" +
                "    \"userInfo\": {\n" +
                "        \"apiKey\": \"c309749450ba443bb59469c562a3b799\",\n" +
                "        \"userId\": \"543192\"\n" +
                "    }\n" +
                "}";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);

        Request request = new Request.Builder()
                .url(json_url)
                .post(requestBody)//请求方式
                .build();

        Call call = client.newCall(request);
        //不能直接更新UI子线程中
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                final String message = e.getMessage();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, ""+message, Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String string = response.body().string();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(MainActivity.this, ""+string, Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });

四.okhttp完成下载文件

 //下载文件到SD卡中
    private void sd() {
        //TODO 1:client
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .callTimeout(5, TimeUnit.SECONDS)
                .build();
        //TODO 2:request
        Request request = new Request.Builder()
                .get()
                .url("http://169.254.113.244/hfs/a.jpg")
                .build();
        //TODO 3:call
        Call call = client.newCall(request);
        //TODO 4:response
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {//失败

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {//成功
                ResponseBody body = response.body();
                long l = body.contentLength();//获得总大小
                InputStream inputStream = body.byteStream();//响应体-->输入流
              	//边读边写
              	//。。。。。
            }
        });
    }

五.okhttp完成上传文件

  private void upload() throws IOException {
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(5, TimeUnit.SECONDS)
                .readTimeout(5, TimeUnit.SECONDS)
                .build();
        //上传文件的请求体
        MultipartBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "aaaa.mp3",//aaaa.mp3 服务器端的名字
                        RequestBody.create(MediaType.parse("media/mp3"), new File("/sdcard/来自天堂的魔鬼.mp3")))
                .build();
        final Request request = new Request.Builder()
                .url("http://172.21.79.88/hfs")
                .post(requestBody)//post提交必须要设置请求体
                .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 {
                
            }
        });
    }

六.okhttp封装

在这里插入图片描述

1.定义回调接口

public interface MyOkListener {
     void onError(String mesage);//返回错误信息
      void onSuccess(String json);//返回数据
}
public interface MyFileListener {

    void setProgress(int progress);//设置当前进度
    void onFinish();//下载完成
    void onError(String message);//错误
}

2.工具类

/**
 * 原则:代码复用性+只有一个Client对象
 *
 *
 * */
public class OkhttpUtils {
    private OkHttpClient okHttpClient;//在构造方法里面创建

    //单例模式:构造私有化
    private OkhttpUtils(){//只会创建一次
        //log拦截器
        HttpLoggingInterceptor httpLoggingInterceptor=new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        //token拦截器
        Interceptor tokenInterceptor=new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
//                Request request = chain.request();//获得request对象
//                Request.Builder builder = request.newBuilder();//通过request获得builder
//                builder.header("token","1705B");//设置请求头
//                Request request1 = builder.build();//添加了token的request
                Request request1=chain.request().newBuilder().header("token","1705B").build();
                return chain.proceed(request1);
            }
        };
        okHttpClient=new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .connectTimeout(5, TimeUnit.SECONDS)
                .addInterceptor(tokenInterceptor)//添加token拦截器,一定要在log拦截器之前设置
                .addInterceptor(httpLoggingInterceptor)//添加log拦截器
                .build();

    };
    //自行实例化
    private static voliate  OkhttpUtils okhttpUtils=null;
    //公开方法
    public static OkhttpUtils getInstance(){
        //双重校验锁:
        if(okhttpUtils==null){
            synchronized (StringBuilder.class){
                if(okhttpUtils==null){
                    okhttpUtils=new OkhttpUtils();
                }
            }
        }
        return  okhttpUtils;
    }
    /***
     * @param str_url  网址
     * @param listener  回调 将请求的结果返回给Activitt
     */
    public  void doget(String str_url, final MyOkListener listener){
        //TODO 2:request对象
        Request request=new Request.Builder().url(str_url).get().header("Connection","Keep-Alive").build();
        //TODO 3:call
        Call call = okHttpClient.newCall(request);
        //TODO 4:加入队列 得到response
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onSuccess(response.body().string());
            }
        });
    }
    /***
     *
     * @param str_url 请求网址
     * @param listener 回调的监听
     * @param map  请求体参数
     */
    public void dopost(String str_url, HashMap<String,String> map, final MyOkListener listener){
        //TODO 请求体
        FormBody.Builder builder1 = new FormBody.Builder();
        Set<Map.Entry<String, String>> entries = map.entrySet();//键值对的集合
        for (Map.Entry<String, String> entry : entries) {//遍历集合
            String key = entry.getKey();//获得键
            String value = entry.getValue();//获得值
            builder1.add(key,value);
        }
        FormBody formBody = builder1.build();
        //TODO 2:request对象
        Request request = new Request.Builder().url(str_url).post(formBody).build();
        //TODO 3:call
        Call call = okHttpClient.newCall(request);
        //TODO 4:加入队列 得到response
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onSuccess(response.body().string());
            }
        });
    }

    /***
     * @param str_url 网址
     * @param path 下载地址
     * @param listener 监听
     */
    public void download(String str_url, final String path, final MyFileListener listener){
        //TODO 1:request对象
        Request request = new Request.Builder()
                .url(str_url)
                .get()
                //③”Accept-Encoding”, “identity”
                .header("Accept-Encoding","identity")
                .build();
        //TODO 2:客户端发起连接得到call
        Call call = okHttpClient.newCall(request);
        //TODO 3:加入队列得到response
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                //TODO 1:获得总长度
                long max = body.contentLength();
            
                //TODO 2:得到输入流
                InputStream inputStream = body.byteStream();
                FileOutputStream fileOutputStream = new FileOutputStream(path);
                byte[] bytes=new byte[1024];
                int len=0;
                int count=0;
                while((len=inputStream.read(bytes))!=-1){
                    fileOutputStream.write(bytes,0,len);
                    count+=len;
                   	int progress= count*100/max;
                    listener.setProgress(progress);//通知进度
                }
                listener.onFinish();//通知完成
            }
        });


    }

    /****
     *
     * @param str_url 请求网址
     * @param path 上传文件的路径
     * @param filename  上传到服务器那边生成文件的名称
     * @param type  类型
     * @param listener  监听
     */
    public void upload(String str_url, String path, String filename,String type, final MyFileListener listener){
        //请求体如何设置
        MultipartBody body=new MultipartBody.Builder()
                .setType(MultipartBody.FORM)//设置方式
                .addFormDataPart("file",filename, RequestBody.create(MediaType.parse(type),new File(path)))
                .build();
        //---------------------
        Request request=new Request.Builder().url(str_url).post(body).build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                listener.onError(e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                listener.onFinish();
            }
        });

    }
}

3. model层编写

public interface OkHttpModel {
     void get(String str_url, MyOkListener listener);
     void post(String str_url, HashMap<String,String> map,MyOkListener listener);
     void download(String str_url, String path, MyFileListener listener);
     void upload(String str_url,String path,String filename,String type,MyFileListener listener);
}

public class OkHttpModelIpml implements OkHttpModel {
    @Override
    public void get(String str_url, MyOkListener listener) {
        OkhttpUtils.getInstance().doget(str_url,listener);
    }

    @Override
    public void post(String str_url, HashMap<String, String> map, MyOkListener listener) {
        OkhttpUtils.getInstance().dopost(str_url,map,listener);
    }

    @Override
    public void download(String str_url, String path, MyFileListener listener) {
        OkhttpUtils.getInstance().download(str_url,path,listener);
    }

    @Override
    public void upload(String str_url, String path, String filename, String type,MyFileListener listener) {
        OkhttpUtils.getInstance().upload(str_url,path,filename,type,listener);
    }
}

5.activity调用

private void post() {
        //请求体
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", "13594347817");
        map.put("passwd", "123654");
        model.post("https://www.apiopen.top/login?key=00d91e8e0cca2b76f515926a36db68f5&", map,
                new MyOkListener() {
                    @Override
                    public void onError(final String mesage) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "" + mesage, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onSuccess(final String json) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(MainActivity.this, "" + json, Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
    }

练习手册:

题目一:

使用okhttp post请求数据,完成建材网项目首页功能,自己安装app
①首页轮播图,UI 100%还原,使用banner完成
②首页中间菜单,UI 100%还原
③首页下面产品分类,UI 100%还原
④点击中间菜单图标,弹出对话框是否下载图标,下载图标到SD卡中
⑤对okhttp进行封装
⑥设置拦截器
⑦设置token拦截器

在这里插入图片描述

题目二:

1.使用okhttp下载一个视频,并显示进度条
http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4
2.使用okhttp上传文件到自己的hfs服务器中

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值