Okhttp学习及封装

Okhttp学习及封装Okhttp1.学习Okhttp2.OkHttp的封装1.学习Okhttp需要导入依赖implementation’com.squareup.okhttp3:okhttp:3.12.1’四个按钮需要写入布局get请求,post请求,下载文件,上传文件别忘了加入SD卡权限,网络权限privatevoidinitView(){get=(Button)…

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

1.学习Okhttp

需要导入依赖

 implementation 'com.squareup.okhttp3:okhttp:3.12.1'

四个按钮需要写入布局
get请求,post请求,下载文件,上传文件
别忘了加入SD卡权限,网络权限

  private void initView() { 
   
        get = (Button) findViewById(R.id.get);
        post = (Button) findViewById(R.id.post);
        progressBar = (ProgressBar) findViewById(R.id.progress_bar);



        get.setOnClickListener(new View.OnClickListener() { 
   
            @Override
            public void onClick(View v) { 
   

                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(50, TimeUnit.SECONDS)
                        .readTimeout(50, TimeUnit.SECONDS)
                        .build();

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


                Call call = client.newCall(request);

                call.enqueue(new Callback() { 
   
                    @Override
                    public void onFailure(Call call, final IOException e) { 
   
                        handler.post(new Runnable() { 
   
                            @Override
                            public void run() { 
   
                                Toast.makeText(MainActivity.this, e.getMessage() + "", 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();
                            }
                        });

                    }
                });


            }
        });


        post.setOnClickListener(new View.OnClickListener() { 
   
            @Override
            public void onClick(View v) { 
   
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(50, TimeUnit.SECONDS)
                        .readTimeout(50, TimeUnit.SECONDS)
                        .build();


                FormBody formBody = new FormBody.Builder()
                        .add("page", "1")
                        .build();


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


                Call call = client.newCall(request);
                call.enqueue(new Callback() { 
   
                    @Override
                    public void onFailure(Call call, final IOException e) { 
   
                        handler.post(new Runnable() { 
   
                            @Override
                            public void run() { 
   
                                Toast.makeText(MainActivity.this, e.getMessage() + "", 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();
                            }
                        });
                    }
                });
            }
        });

        download = (Button) findViewById(R.id.download);


        download.setOnClickListener(new View.OnClickListener() { 
   
            @Override
            public void onClick(View v) { 
   
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(50, TimeUnit.SECONDS)
                        .readTimeout(50, TimeUnit.SECONDS)
                        .build();

                Request request = new Request.Builder()
                        .url("http://uvideo.spriteapp.cn/video/2019/0512/56488d0a-7465-11e9-b91b-1866daeb0df1_wpd.mp4")
                        .build();


                Call call = client.newCall(request);

                call.enqueue(new Callback() { 
   
                    @Override
                    public void onFailure(Call call, final IOException e) { 
   
                        handler.post(new Runnable() { 
   
                            @Override
                            public void run() { 
   
                                Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException { 
   
                        ResponseBody body = response.body();
                        maxlen = body.contentLength();

                        InputStream is = body.byteStream();
                        File file = Environment.getExternalStorageDirectory();
                        FileOutputStream fos = new FileOutputStream(new File(file, "猩猩.mp4"));
                        int len = 0;
                        byte[] b = new byte[1024];
                        long carlen = 0;
                        while ((len = is.read(b)) != -1) { 
   
                            fos.write(b, 0, len);

                            carlen += len;
                            int progress = (int) (carlen * 100 / maxlen);
                            progressBar.setProgress(progress);
                        }
                    }
                });
            }
        });

        Upload = (Button) findViewById(R.id.Upload);


        Upload.setOnClickListener(new View.OnClickListener() { 
   
            @Override
            public void onClick(View v) { 
   
                OkHttpClient client = new OkHttpClient.Builder()
                        .connectTimeout(50, TimeUnit.SECONDS)
                        .readTimeout(50, TimeUnit.SECONDS)
                        .build();

                File file = Environment.getExternalStorageDirectory();
                RequestBody requestBody = RequestBody.create(MediaType.parse("media/mp4"), new File(file, "猩猩.mp4"));



                MultipartBody multipartBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file","xingxing.mp4",requestBody)
                        .build();


                Request request = new Request.Builder()
                        .url("http://169.254.141.30/hfs/")
                        .post(multipartBody)
                        .build();


                Call call = client.newCall(request);
                call.enqueue(new Callback() { 
   
                    @Override
                    public void onFailure(Call call, final IOException e) { 
   
                        handler.post(new Runnable() { 
   
                            @Override
                            public void run() { 
   
                                Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException { 
   
                        handler.post(new Runnable() { 
   
                            @Override
                            public void run() { 
   
                                Toast.makeText(MainActivity.this,   "上传成功", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }
                });
            }
        });

    }

2.OkHttp的封装

代码之路很艰辛,依照上面的方法我们不能重复写的代码
可一给他封装一个工具类
我们用到了单利模式
主类直接调用就行

   private OkHttpClient client;
    private Handler handler=new Handler();

    private MyOkUtiles() { 
   
         client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
    }

    private static MyOkUtiles myOkUtiles=null;


    public static MyOkUtiles getInstance(){ 
   
        if (myOkUtiles==null){ 
   
            synchronized (Object.class){ 
   
                if (myOkUtiles==null){ 
   
                    myOkUtiles=new MyOkUtiles();
                }
            }
        }
        return myOkUtiles;
    }


    public void get(String url, final MyOkListener myOkListener){ 
   

        Request request = new Request.Builder()
                .url(url)
                .get().build();

        client.newCall(request).enqueue(new Callback() { 
   
            @Override
            public void onFailure(Call call, IOException e) { 
   
                final String message = e.getMessage();
                handler.post(new Runnable() { 
   
                    @Override
                    public void run() { 
   
                        myOkListener.MyError(message);
                    }
                });

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException { 
   
                final String string = response.body().string();
                handler.post(new Runnable() { 
   
                    @Override
                    public void run() { 
   
                        myOkListener.MyOk(string);
                    }
                });
            }
        });
    }

    public void post(String url, HashMap<String,String> map, final MyOkListener myOkListener){ 
   
        FormBody.Builder builder = new FormBody.Builder();
        HashMap<String, String> maps = new HashMap<>();
        Set<Map.Entry<String, String>> entries = maps.entrySet();
        for (Map.Entry<String, String> entry : entries) { 
   
            builder.add(entry.getKey(),entry.getValue());
        }

        Request request = new Request.Builder()
                .url(url)
                .post(builder.build())
                .build();


        client.newCall(request).enqueue(new Callback() { 
   
            @Override
            public void onFailure(Call call, IOException e) { 
   
                final String message = e.getMessage();
                handler.post(new Runnable() { 
   
                    @Override
                    public void run() { 
   
                        myOkListener.MyError(message);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException { 
   
                final String string = response.body().string();
                handler.post(new Runnable() { 
   
                    @Override
                    public void run() { 
   
                        myOkListener.MyOk(string);
                    }
                });
            }
        });

    }


    public void download(String url, final String path, final MyProgressListener myProgressListener){ 
   

        Request request = new Request.Builder()
                .url(url)
                .get().build();


        client.newCall(request).enqueue(new Callback() { 
   
            @Override
            public void onFailure(Call call, IOException e) { 
   
                final String message = e.getMessage();
                handler.post(new Runnable() { 
   
                    @Override
                    public void run() { 
   
                       myProgressListener.MyError(message);
                    }
                });
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException { 
   
                ResponseBody body = response.body();
                final long maxLen = body.contentLength();
                InputStream is = body.byteStream();

                FileOutputStream fos = new FileOutputStream(path);
                int len=0;
                byte[] b = new byte[1024];
                long carlen=0;
                while ((len=is.read(b))!=-1){ 
   
                     fos.write(b,0,len);

                     carlen+=len;
                     final int progress= (int) (carlen*100/maxLen);
                     handler.post(new Runnable() { 
   
                         @Override
                         public void run() { 
   
                             myProgressListener.Progress(progress);
                         }
                     });
                }

                handler.post(new Runnable() { 
   
                    @Override
                    public void run() { 
   
                        myProgressListener.Finish();
                    }
                });
            }
        });
    }


    public void upload(String url, String path, String servername, String type, final MyOkListener myOkListener){ 
   


        RequestBody requestBody = RequestBody.create(MediaType.parse(type), new File(path));

        MultipartBody multipartBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", servername, requestBody)
                .build();

        Request request = new Request.Builder()
                .url(url)
                .post(multipartBody)
                .build();



        client.newCall(request).enqueue(new Callback() { 
   
            @Override
            public void onFailure(Call call, IOException e) { 
   
                final String message = e.getMessage();
                handler.post(new Runnable() { 
   
                    @Override
                    public void run() { 
   
                        myOkListener.MyError(message);
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException { 
   
                if (response.isSuccessful()) { 
   
                    handler.post(new Runnable() { 
   
                        @Override
                        public void run() { 
   
                           myOkListener.MyOk("成功");
                        }
                    });
                }else { 
   
                    handler.post(new Runnable() { 
   
                        @Override
                        public void run() { 
   
                            myOkListener.MyOk("失败");
                        }
                    });
                }
            }
        });


    }
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/180465.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • 下载pycharm安装教程_tc简单程序开发工具教程

    下载pycharm安装教程_tc简单程序开发工具教程Pycharm可以说是一款进行Python开发功能强大的编辑器。鉴于近期很少有关最新版本的Pycharm安装教程,为了能够帮助刚刚学习Python的朋友们。宋宋老师又给大家准备了一版,会介绍Pycharm的安装和注意事项,希望能够在大家学习Python的道路上起到一点微薄之力。文章分为四部分: Pycharm简介 Pycharm下载 Pycharm安装 Pycharm配置 Pycharm简介PyCharm是由JetBrains打造的一款PythonIDE,J

  • MySQL数据库管理工具_Mysql数据库

    MySQL数据库管理工具_Mysql数据库官方社区版免费工具MySQLWorkbenchMySql官方社区版下载:MySQLCommunityDownloadsMySQLYumRepository MySQLAPTRepository MySQLSUSERepository MySQLCommunityServer MySQLCluster MySQLRouter MySQLShell MySQLWorkbench MySQLInstallerforWind…

  • 【windows屏幕扩展】把你多余屏幕利用起来,spacedesk屏幕扩展超低延迟解决方案[通俗易懂]

    【windows屏幕扩展】把你多余屏幕利用起来,spacedesk屏幕扩展超低延迟解决方案[通俗易懂]目录扫盲扫盲spacedesk是一款基于TCP/IP协议的屏幕扩展工具,通过这款工具你可以把自己身边的闲置的平板手机或者笔记本利用起来,扩展你的屏幕。只要你的两台设备处于同一个网络环境下(只要互相能够ping通),你就可以实现屏幕扩展(卡不卡我就不知道了)。用过win10中的wifi扩展屏幕的同学都知道,扩展的屏幕显示质量和网络环境成正比。而win10的屏幕扩展很玄学,…

  • JAVA实现二维码扫码登录「建议收藏」

    实现客户端扫码登录分为下列四步.

  • 三条平行线与等边三角形

    三条平行线与等边三角形偶然在网上看到一道有意思的几何题,仔细思考了一下,确实有点趣。原题是:平面上有任意三条平行线,使用尺规则作图画出一个等边三角形,使三角形的三个顶点分别在三条平行线上。画法有好多种,搜集网上的一些画法,先介绍4种,再讨论一下三角形连长与平等线距离的关系,最后讨论下第二种画法的变化(三角形边长的唯一性未证明)。第一种:作图顺序:(颜色顺序:红—>绿—>蓝—>紫)1.在三条…

  • Ffmpeg进行视频文件转换

    Ffmpeg进行视频文件转换

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号