Okhttp3使用

历史发展

Okhttp是一个处理网络请求的开源项目,是安卓最火热的轻量级框架,Retrofit底层也是使用Okhttp,接下来长话短说,来给大家讲解一下

导入

gradle方式:

    //1、添加okhttp的依赖
    compile 'com.squareup.okhttp3:okhttp:3.9.0'
    //2、json数据解析的工具
    compile 'com.google.code.gson:gson:2.2.4'

基本用法

  • 简单使用方法:首先,如果要设置设置超时时间和缓存,要通过OkHttpClient.Builder来设置
  OkhttpClient client = new OkHttpClient
                    .Builder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .writeTimeout(10,TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .build();
  • Get请求
     /**
     * 同步请求  方法里面的第二个参数是一个接口,
     * 可以自行写一个接口目的是实现接口直接获取请求后的数据
     */
    public void getOkHttp(String url, final ImpLoadGet imp) {
        //调用ok的get请求
        Request request = new Request.Builder()
                .get()
                .url(url)
                .build();
        final Call call = client.newCall(request);
        //同步execute
        //同步请求
        //同步是耗时的
        //同步execute需要开启子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        //调用者只需要实现provide方法就能拿到这个String了
                        imp.getLoad(string);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

   /**
     * get拼接传值方法
     * @param url ?username=xxxx&password=xxx
     */
    public void getOkHttp(String url, Map<String, String> map, Callback callback) {
        StringBuffer sb = new StringBuffer();
        String string = "";
        String result = "";
        //当用户传入null或者传了一个空的map
        if (map != null && !map.isEmpty()) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                if (sb == null) {
//                    sb = new StringBuffer ();
                    sb.append("?");
                } else {
                    //拼接好的网站去掉最后一个“&”符号
                    sb.append("&");
                }
                sb.append(entry.getKey() + "=" + entry.getValue());
            }
        }
        if (sb.toString() != null) {
            string = sb.toString();
            Log.e("", string);
            result = url + string;
            Log.e("", result);
        }
        Request request = new Request.Builder()
                .get() //声明我是get请求,如果不写默认就是get
                .url(string == "" ? url : result)//声明网站访问的网址
                .build();//创建Request
        Call call = client.newCall(request);
        //同步execute,异步enqueue
        //这里的同步是耗时的
        //而且OK 也没有为我们开启子线程‘
        // 如果你用同步方法的话,需要开启子线程
        call.enqueue(callback);
    }

response的body有很多种输出方法,string()只是其中之一,注意是string()不是toString()。如果是下载文件就是response.body().bytes()。
另外可以根据response.code()获取返回的状态码。

  • Post请求

1.普通请求参数方法

    public void postOkhttp(String url, Map<String, String> map, Callback callBack) {
        //上传文字格式 数据的传输,区别于多媒体输出
        FormBody.Builder formbody = new FormBody.Builder();
        if (map != null && !map.isEmpty()) {
            //上传参数
            for (String key : map.keySet()) {
                formbody.add(key, map.get(key));
            }
            //创建请求体
            FormBody body = formbody.build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)//请求体
                    .build();
            Call call = client.newCall(request);
            //异步请求方式
            call.enqueue(callBack);
        } else {
            //创建请求体
            FormBody body = formbody.build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            Call call = client.newCall(request);
            //异步请求方式
            call.enqueue(callBack);
        }
    }

2.文件和参数请求方法

 /**
     * MultipartBody:用来提交包涵文件的参数
     * 
     * @param path    :路径
     * @param map     :普通参数
     * @param img     :提交文件的关键字
     * @param imgPath :提交文件的路径
     */
    public void postFileOkhttp(String path, HashMap<String, String> map, String img, String imgPath, Callback callBack) {
        MultipartBody.Builder requestBody = new MultipartBody.Builder();
        if (map!=null && !map.isEmpty()) {
            //上传参数
            for (String key : map.keySet()) {
                requestBody.addFormDataPart(key, map.get(key));
            }
            File file = new File(imgPath);
            requestBody.addFormDataPart(img, file.getPath()
                    , RequestBody.create(MediaType.parse("image/png"), file));
            Request request = new Request.Builder()
                    .post(requestBody.build())
                    .url(path)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callBack);
        }else{
            File file = new File(imgPath);
            requestBody.addFormDataPart(img, file.getPath()
                    , RequestBody.create(MediaType.parse("image/png"), file));
            Request request = new Request.Builder()
                    .post(requestBody.build())
                    .url(path)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callBack);
        }
    }

3.多文件和参数的请求方法

 /**
     * MultipartBody:用来提交包涵文件的参数
     * 多文件上传
     */
    public void postFileOkhttp2(String path, HashMap<String, String> map, String img, List<String> imgPths, Callback callBack) {
        MultipartBody.Builder requestBody = new MultipartBody.Builder();
        if (map != null && !map.isEmpty()) {

            //上传参数
            for (String key : map.keySet()) {
                requestBody.addFormDataPart(key, map.get(key));
            }
            //遍历paths中所有图片绝对路径到builder,并约定key如“upload”作为后台接受多张图片的key
            if (imgPths != null) {
                for (String string : imgPths) {
                    File file = new File(string);
                    requestBody.addFormDataPart(img, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
                }
            }

            Request request = new Request.Builder()
                    .post(requestBody.build())
                    .url(path)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callBack);
        }else{
            //遍历paths中所有图片绝对路径到builder,并约定key如“upload”作为后台接受多张图片的key
            if (imgPths != null) {
                for (String string : imgPths) {
                    File file = new File(string);
                    requestBody.addFormDataPart(img, file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
                }
            }

            Request request = new Request.Builder()
                    .post(requestBody.build())
                    .url(path)
                    .build();
            Call call = client.newCall(request);
            call.enqueue(callBack);
        }
   }

学习能力还不够完善,基本使用方法已经上传到github上,有兴趣的可以下载看看,代码很整洁

2018.5.9更新

1.新添加了上传文件和多参数的方法
2.新添加了上传多文件和多参数的方法

github: https://github.com/github5210zk/Okhttp3/tree/master


各位大神好,麻烦看到后觉的哪里有错的,指正一下,拜托了大家。
  • 4
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 8
    评论
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值