OkHttp3详解

OkHttp3 官网 & website

1.Http协议简介

客户端向服务器发送一个Request,服务端收到Request并进行一系列的处理,返回给客户端一个Response
这里写图片描述

Http状态码简介(code为三位数)
1xx(临时响应) 2xx (成功)3xx (重定向) 4xx(请求错误)5xx(服务器错误)

2.快速使用(AndroidStudio)

①添加依赖 compile ‘com.squareup.okhttp3:okhttp:3.8.1’
②添加网络权限
③GET请求

    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) {
            Log.e(TAG, "onFailure: "+ e.getLocalizedMessage());
        }

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

            String result = response.body().string();
            Log.e(TAG, "onResponse: "+result);


            // 用完关闭资源
            if (response.body()!=null){
                response.body().close();
            }
         }
     });

④Response里有这么两个方法

    // response.isSuccessful();是否连接成功 状态码2xx
    // response.isRedirect();是否重定向 状态码3xx

⑤Post请求(form表单)

    OkHttpClient client = new OkHttpClient();

    // post请求需要传入一个RequestBody对象
    // 直接点进去RequestBody,通过查看源码发现RequestBody是个抽象类
    // RequestBody右键-->Go To-->Implementation(s)
    // 发现有两个具体实现类 FormBody(表单) MultiparBody(多种提交方式包括表单、文件等)
    RequestBody body;

    body = new FormBody.Builder().add("phone","12345678900").build();

    Request request = new Request.Builder().url(postPath).post(body).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 {

    });

⑥Post(json形式)

    OkHttpClient client = new OkHttpClient();

    // json字符串  {"phone":"1234678900"}
    String jsonParams = new Gson().toJson(new Phone("1234678900"));

    RequestBody body = RequestBody.create(MediaType.parse("application/json"),jsonParams);

    Request request = new Request.Builder().url(postPath).post(body).build();
    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        }
    });

⑦文件上传(表单形式上传文字和图片)

    OkHttpClient client = new OkHttpClient();

    String basePath = Environment.getExternalStorageDirectory().getAbsolutePath();

    RequestBody fileBody1 = RequestBody.create(MediaType.parse("image/png"),new File(basePath+"img1.png"));
    RequestBody fileBody2 = RequestBody.create(MediaType.parse("image/png"),new File(basePath+"img2.png"));

    // .addFormDataPart("idcard_front_img","1",fileBody1)
    // 此处传"1",可能会在后台生成图片名.1这种形式的文件
    // 为了便于管理可以写成addFormDataPart("idcard_front_img","png",fileBody1)
    // 传null可能会导致调用fail方法
    RequestBody body = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("idcard_no","130233199560509xxxx")
        .addFormDataPart("idcard_front_img","1",fileBody1)
        .addFormDataPart("idcard_behind_img","2",fileBody2)
        .build();

    Request request = new Request.Builder().url(imgPostPath).post(body).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 {

            Log.d(TAG,"上传成功");
        }
    });

⑧文件下载

    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(downLoadPath).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 is = null;
            FileOutputStream fos = null;

            is = response.body().byteStream();
            fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"xxx.apk"));

            byte[] b = new byte[1024];
            int len = 0;

            while ((len = is.read(b))!=-1){
                fos.write(b,0,len);
                fos.flush();
            }

            is.close();
            fos.close();
        }
    });

⑨源码与效果 点我下载源码

这里写图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值