OkHttp二次封装
来源:互联网 发布:iyst是什么预算软件 编辑:程序博客网 时间:2024/06/05 03:02
//Okhttp依赖 compile 'com.squareup.okio:okio:1.5.0' compile 'com.squareup.okhttp3:okhttp:3.2.0' //拦截器 compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
- 1
- 2
- 3
- 4
- 5
//和上一次的对比主要更新了文件上传 并且保存了第一次上传文件的方法 新增网络拦//截器 public class OkHttp3Utils { private static OkHttpClient okHttpClient = null; public OkHttp3Utils() { } //通过单例模式获取实例 public static OkHttpClient getInstance() { if (okHttpClient == null) { //同步代码 synchronized (OkHttp3Utils.class) { if (okHttpClient == null) { //缓存路径 File sdcache = new File(Environment.getExternalStorageDirectory(), "wybcache"); int cacheSize = 10 * 1024 * 1024; //okhttp拦截器 HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { Log.i("msg", message.toString()); } }); //拦截器日志分类 httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); okHttpClient = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.MINUTES) .addInterceptor(httpLoggingInterceptor) ..addNetworkInterceptor(new CacheInterceptor()) //如果网络拦截器 一下要注释掉 .cache(new Cache(sdcache.getAbsoluteFile(), cacheSize)) .build(); } } } return okHttpClient; } /** * get请求方式 * * @param url 请求地址 * @param callback 回调接口 */ public static void doGet(String url, Callback callback) { //获取请求对象的实例 OkHttpClient okHttpClient = OkHttp3Utils.getInstance(); //创建Request Request request = new Request.Builder().url(url).build(); //得到Call Call call = okHttpClient.newCall(request); //执行异步请求 call.enqueue(callback); } public static void doGetHeader(String url,Map<String,String> headers, Callback callback) { //获取请求对象的实例 OkHttpClient okHttpClient = OkHttp3Utils.getInstance(); //创建Request Request.Builder builder = new Request.Builder(); builder.url(url); for (String header:headers.keySet()) { builder.addHeader(header,headers.get(header)); } Request request=builder.build(); //得到Call Call call = okHttpClient.newCall(request); //执行异步请求 call.enqueue(callback); } /** * post请求方式 * * @param url 请求地址 * @param params 请求体 * @param callback 接口回调 */ public static void doPost(String url, Map<String, String> params, Callback callback) { //获取请求对象的实例 OkHttpClient okHttpClient = OkHttp3Utils.getInstance(); //3.x版本post请求换成FormBody 封装键值对参数 FormBody.Builder builder = new FormBody.Builder(); //遍历map集合给请求体添加值 for (String key : params.keySet()) { builder.add(key, params.get(key)); } //创建Request Request request = new Request.Builder().url(url).post(builder.build()).build(); //获取call Call call = okHttpClient.newCall(request); //异步请求 call.enqueue(callback); } public static void doPostHeader(String url,Map<String,String> headers, Map<String, String> params, Callback callback) { //获取请求对象的实例 OkHttpClient okHttpClient = OkHttp3Utils.getInstance(); //3.x版本post请求换成FormBody 封装键值对参数 FormBody.Builder builder = new FormBody.Builder(); //遍历map集合给请求体添加值 for (String key : params.keySet()) { builder.add(key, params.get(key)); } //创建Request //创建Request Request.Builder builder1 = new Request.Builder(); builder1.url(url); for (String header:headers.keySet()) { builder1.addHeader(header,headers.get(header)); } Request request = builder1.post(builder.build()).build(); //获取call Call call = okHttpClient.newCall(request); //异步请求 call.enqueue(callback); } /** * 上传文件 * * @param url 接口地址 * @param file 文件 * @param fileName 文件名 */ public static void loadFile(String url, File file, String fileName,Callback callback) { //创建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 = okHttpClient.newCall(request); call.enqueue(callback); } /** * post请求上传文件 * 参数1 url * 参数2 回调Callback */ public static void uploadPic(String url, Map<String, Object> params,Callback callback) { //创建OkHttpClient请求对象 OkHttpClient okHttpClient = getInstance(); //创建MultipartBody.Builder MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM); for (Map.Entry<String, Object> entry : params.entrySet()) { Object value = entry.getValue(); if (value instanceof File) { File file = (File) value; //创建RequestBody 封装file参数 builder.addFormDataPart(entry.getKey(), file.getName(), RequestBody.create(MediaType.parse("application/octet-stream"), file)); } else { builder.addFormDataPart(entry.getKey(), value.toString()); } } //创建RequestBody 设置类型等 RequestBody requestBody = builder.build(); //创建Request Request request = new Request.Builder().url(url).post(requestBody).build(); //得到Call Call call = okHttpClient.newCall(request); //执行请求 call.enqueue(callback); } /** * 上传json字符 * * @param url 接口地址 * @param jsonParams Json串 * @param callback 接口回调 */ 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); } /** * 下载 * * @param context * @param url 下载地址 * @param saveDir 保存的位置 */ public static void downFile(final Activity context, final String url, final String saveDir) { //创建Request Request request = new Request.Builder().url(url).build(); //创建Call 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); } /** * 为okhttp添加缓存,这里是考虑到服务器不支持缓存时,从而让okhttp支持缓存 */ private static class CacheInterceptor implements Interceptor { @Override public Response intercept(Chain chain) throws IOException { // 有网络时 设置缓存超时时间1个小时 int maxAge = 60 * 60; // 无网络时,设置超时为1天 int maxStale = 60 * 60 * 24; Request request = chain.request(); if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) { //有网络时只从网络获取 request = request.newBuilder().cacheControl(CacheControl.FORCE_NETWORK).build(); } else { //无网络时只从缓存中读取 request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build(); /* Looper.prepare(); Toast.makeText(MyApp.getInstance(), "走拦截器缓存", Toast.LENGTH_SHORT).show(); Looper.loop();*/ } Response response = chain.proceed(request); if (NetWorkUtils.isNetWorkAvailable(MyApp.getInstance())) { response = response.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public, max-age=" + maxAge) .build(); } else { response = response.newBuilder() .removeHeader("Pragma") .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale) .build(); } return response; } }}
- 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
- 251
- 252
- 253
- 254
- 255
- 256
- 257
- 258
- 259
- 260
- 261
- 262
- 263
- 264
- 265
- 266
- 267
- 268
- 269
- 270
- 271
- 272
- 273
- 274
- 275
- 276
- 277
- 278
- 279
- 280
- 281
- 282
- 283
- 284
- 285
- 286
- 287
- 288
- 289
- 290
- 291
- 292
- 293
- 294
- 295
- 296
- 297
- 298
- 299
- 300
- 301
- 302
- 303
- 304
- 305
- 306
- 307
- 308
判断网络工具类
//判断网络工具类public class NetWorkUtils { //判断网络是否连接 public static boolean isNetWorkAvailable(Context context) { //网络连接管理器 ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); //网络信息 NetworkInfo info = connectivityManager.getActiveNetworkInfo(); if (info != null) { return true; } return false; }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
全局配置
//全局配置public class MyApp extends Application { public static MyApp mInstance; @Override public void onCreate() { super.onCreate(); mInstance = this; } public static MyApp getInstance() { return mInstance; }}//注意清单文件//权限 <uses-permission android:name="android.permission.INTERNET"></uses-permission><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission><application android:name=".app.MyApp" ... </application>
阅读全文
0 0
- OkHttp的二次封装
- okhttp的二次封装
- okhttp二次封装
- Okhttp的二次封装
- Okhttp二次封装
- okhttp二次封装
- okHttp二次封装
- Okhttp二次封装
- OkHttp二次封装
- Okhttp二次封装
- 二次封装oKHTTP
- OKhttp二次封装
- OkHttp的二次封装
- OkHttp二次封装类
- okhttp的二次封装
- OkHttp的二次封装
- okhttp的二次封装
- OkHttp二次封装
- 注册表------数据结构--数据库
- cmd编译运行java无法加载主类(前提:环境变量没问题,主函数没问题)
- leetcode 19 题解 翻译 Python版
- C#3.0 之扩展方法
- Md5Util 加密工具类
- OkHttp二次封装
- 域名系统DNS总结
- 剑指offer 50 把字符串转换成整数
- hiho一下 第173周 题目1 : A Game 【区间dp】
- 【20171025中】alert(1) to win 脚本渲染自建
- 转载安装theano后GPU配置的各种坑
- Linux基础
- opencv的二值化1( 用Otsu’s二值化,找到双峰阈值)
- DOM技术