二次封装oKHTTP

来源:互联网 发布:天天酷跑解封软件 编辑:程序博客网 时间:2024/06/05 08:43

1.先导依赖
compile ‘com.squareup.okio:okio:1.5.0’
compile ‘com.squareup.okhttp3:okhttp:3.2.0’

2.在创建要工具包和工具类
下面就是二次封装的工具类直接调用即可

package com.bwei.okhttp3ps.utils;import android.content.Intent;import android.net.Uri;import android.os.Environment;import android.util.Log;import android.widget.Toast;import com.bwei.okhttp3ps.activity.MainActivity;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Map;import java.util.concurrent.TimeUnit;import okhttp3.Cache;import okhttp3.Call;import okhttp3.Callback;import okhttp3.FormBody;import okhttp3.MediaType;import okhttp3.MultipartBody;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.RequestBody;import okhttp3.Response;/** * 1. 类的用途 封装OkHttp3的工具类 用单例设计模式 * 2. @author forever * 3. @date 2017/9/6 09:19 */public class OkHttp3Utils {    /**     * 懒汉 安全 加同步     * 私有的静态成员变量 只声明不创建     * 私有的构造方法     * 提供返回实例的静态方法     */    private static OkHttpClient okHttpClient = null;    private OkHttp3Utils() {    }    public static OkHttpClient getInstance() {        if (okHttpClient == null) {            //加同步安全            synchronized (OkHttp3Utils.class) {                if (okHttpClient == null) {                    //判空 为空创建实例                    // okHttpClient = new OkHttpClient();/** * 和OkHttp2.x有区别的是不能通过OkHttpClient直接设置超时时间和缓存了,而是通过OkHttpClient.Builder来设置, * 通过builder配置好OkHttpClient后用builder.build()来返回OkHttpClient, * 所以我们通常不会调用new OkHttpClient()来得到OkHttpClient,而是通过builder.build(): */                    //  File sdcache = getExternalCacheDir();                    File sdcache = new File(Environment.getExternalStorageDirectory(), "cache");                    int cacheSize = 10 * 1024 * 1024;                    okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS)                            .writeTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).cache(new Cache(sdcache.getAbsoluteFile(), cacheSize)).build();                }            }        }        return okHttpClient;    }    /**     * get请求     * 参数1 url     * 参数2 回调Callback     */    public static void doGet(String url, Callback callback) {        //创建OkHttpClient请求对象        OkHttpClient okHttpClient = getInstance();        //创建Request        Request request = new Request.Builder().url(url).build();        //得到Call对象        Call call = okHttpClient.newCall(request);        //执行异步请求        call.enqueue(callback);    }    /**     * post请求     * 参数1 url     * 参数2 回调Callback     */    public static void doPost(String url, Map<String, String> params, Callback callback) {        //创建OkHttpClient请求对象        OkHttpClient okHttpClient = getInstance();        //3.x版本post请求换成FormBody 封装键值对参数        FormBody.Builder builder = new FormBody.Builder();        //遍历集合        for (String key : params.keySet()) {            builder.add(key, params.get(key));        }        //创建Request        Request request = new Request.Builder().url(url).post(builder.build()).build();    }    /**     * post请求上传文件     * 参数1 url     * 参数2 回调Callback     */    public static void uploadPic(String url, File file, String fileName) {        //创建OkHttpClient请求对象        OkHttpClient okHttpClient = getInstance();        //创建RequestBody 封装file参数        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);        //创建RequestBody 设置类型等        RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, fileBody).build();        //创建Request        Request request = new Request.Builder().url(url).post(requestBody).build();        //得到Call        Call call = okHttpClient.newCall(request);        //执行请求        call.enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                //上传成功回调 目前不需要处理            }        });    }    /**     * Post请求发送JSON数据     * 参数一:请求Url     * 参数二:请求的JSON     * 参数三:请求回调     */    public static void doPostJson(String url, String jsonParams, Callback callback) {        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonParams);        Request request = new Request.Builder().url(url).post(requestBody).build();        Call call = getInstance().newCall(request);        call.enqueue(callback);    }    /**     * 下载文件 以流的形式把apk写入的指定文件 得到file后进行安装     * 参数一:请求Url     * 参数二:保存文件的路径名     * 参数三:保存文件的文件名     */    public static void download(final MainActivity context, final String url, final String saveDir) {        Request request = new Request.Builder().url(url).build();        Call call = getInstance().newCall(request);        call.enqueue(new Callback() {            @Override            public void onFailure(Call call, IOException e) {                Log.i("xxx", e.toString());            }            @Override            public void onResponse(Call call, final Response response) throws IOException {                InputStream is = null;                byte[] buf = new byte[2048];                int len = 0;                FileOutputStream fos = null;                try {                    is = response.body().byteStream();                    //apk保存路径                    final String fileDir = isExistDir(saveDir);                    //文件                    File file = new File(fileDir, getNameFromUrl(url));                    context.runOnUiThread(new Runnable() {                        @Override                        public void run() {                            Toast.makeText(context, "下载成功:" + fileDir + "," + getNameFromUrl(url), Toast.LENGTH_SHORT).show();                        }                    });                    fos = new FileOutputStream(file);                    while ((len = is.read(buf)) != -1) {                        fos.write(buf, 0, len);                    }                    fos.flush();                    //apk下载完成后 调用系统的安装方法                    Intent intent = new Intent(Intent.ACTION_VIEW);                    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");                    context.startActivity(intent);                } catch (IOException e) {                    e.printStackTrace();                } finally {                    if (is != null) is.close();                    if (fos != null) fos.close();                }            }        });    }    /**     * @param saveDir     * @return     * @throws IOException 判断下载目录是否存在     */    public static String isExistDir(String saveDir) throws IOException {        // 下载位置        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {            File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);            if (!downloadFile.mkdirs()) {                downloadFile.createNewFile();            }            String savePath = downloadFile.getAbsolutePath();            Log.e("savePath", savePath);            return savePath;        }        return null;    }    /**     * @param url     * @return 从下载连接中解析出文件名     */    private static String getNameFromUrl(String url) {        return url.substring(url.lastIndexOf("/") + 1);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250

3.网络请求数据

    private void getData() {        OkHttp3Utils.doGet(url, new Callback() {            @Override            public void onFailure(Call call, IOException e) {            }            @Override            public void onResponse(Call call, Response response) throws IOException {                String json = response.body().string();                Message message = handler.obtainMessage(0, json);                message.sendToTarget();            }        });    }
原创粉丝点击