Android联网第三方框架okhttp-3.8.0.jar/okio-1.13.0.jar用法

在依赖中可以用

implementation 'com.yanzhenjie.nohttp:okhttp:+'
//下载文件时需要在依赖:implementation files('libs/okio-1.13.0.jar')

或者用jar包

 implementation files('libs/okhttp-3.8.0.jar')
    implementation files('libs/okio-1.13.0.jar')

"GET"方式请求网络

public void getDataByOKGet() {
        OkHttpClient okHttpClient = new OkHttpClient();//把客户端new出来
        Request.Builder builder = new Request.Builder();//请求建立对象
        try {
            Request request = builder
                    .get()//"GET"方式请求网络
                    .url("http://apicloud.mob.com/environment/query?key=26b2b13b4b440&city="
                            + URLEncoder.encode("哈尔滨","UTF-8")
                            +"&province="
                            +URLEncoder.encode("黑龙江","UTF-8"))
                    .build();//请求对象建立请求
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {//入队
                @Override
                public void onFailure(Call call, IOException e) {
                //当失败时
                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
//                    当响应时
                    runOnUiThread(new Thread(){//在主线程更新UI
                        @Override
                        public void run() {
                            try {
                                mTextView.setText(response.body().string());//从网络上获取的就是JSON
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    });

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

"POST"方式请求网络(所以需要写一个模板,来产生一个请求主体)

public void getDataByOKPost(){
        try {
            OkHttpClient okHttpClient = new OkHttpClient();//OK客户端对象

            FormBody.Builder build = new FormBody.Builder();//建设模板
            RequestBody requestBody = build
                .add("city",URLEncoder.encode("哈尔滨","UTF-8"))
                .add("province",URLEncoder.encode("黑龙江","UTF-8"))
                    .add("key",URLEncoder.encode("26b2b13b4b440","UTF-8"))
                    .build();//用模板.build返回请求主体

            Request.Builder builder = new Request.Builder();//建立请求对象

            Request request = builder
                    .post(requestBody)//"POST"方式请求网络(所以需要写一个模板,来产生一个请求主体)
                    .url("http://apicloud.mob.com/v1/postcode/pcd")
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {
                    final String s = response.body().string();
                    runOnUiThread(new Thread(){
                        @Override
                        public void run() {
                            try {
                                mTextView.setText(s);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });

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


    }

显示图片下载

public void getDataByOKDown(){
        try {
            OkHttpClient okHttpClient = new OkHttpClient();

            FormBody.Builder build = new FormBody.Builder();
            RequestBody requestBody = build.build();
            Request.Builder builder = new Request.Builder();
            Request request = builder
                    .post(requestBody)
                    .url("http://pic2.sc.chinaz.com/files/pic/pic9/201808/zzpic13391.jpg")
                    .build();
            Call call = okHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, final Response response) throws IOException {

                    InputStream is = response.body().byteStream();
                    ByteArrayOutputStream bs = new ByteArrayOutputStream();
                    byte buffer[] = new byte[512];
                    int length = -1;
                    while(  (length = is.read(buffer)) != -1  ){
                        bs.write(buffer,0,length);
                        bs.flush();
                    }

                    final File file = new File(
                            Environment.getExternalStorageDirectory()+"/12331710.jpg");
                    FileOutputStream fs = new FileOutputStream(file);

                    byte data[] = bs.toByteArray();
                    Log.d("data",data.length+"");
                    fs.write(data,0,data.length);
                    fs.flush();
                    is.close();
                    bs.close();
                    fs.close();
                    runOnUiThread(new Thread(){
                        @Override
                        public void run() {
                            Log.d("data",file.getAbsolutePath());
                            mImageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
                        }
                    });
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

https://github.com/microshow/fastokhttp访问下载查看

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 137,251评论 19赞 139
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,411评论 3赞 119
  • 刚好,我想你,你想我;刚好,你遇见我,我遇见你;刚好,那天时间刚好,那天天气刚好,那天,我们刚刚好。...
    孟小苒阅读 789评论 12赞 10
  • 今天是持续的雨天,而且夹杂着大风,一大早要坐半个小时去上日语课,心情还是明朗很多的 上完日语课回来的路上简直狂风肆...
    相爱有时阅读 1,591评论 0赞 0
  • 考场里的人本来就不多,加上我刚好十个。默不作声的考生们更是为考场平添了一股紧张的气氛。还未静下心的我望着洁白...
    Archer_015阅读 137评论 0赞 0

友情链接更多精彩内容