标签:looper 请求 声明 public header 管理 body sink code
官网地址:http://square.github.io/okhttp/
github地址:
参考博客:Android okHttp网络请求之Get/Post请求
参考博客:Android okHttp网络请求之文件上传下载
session相关博客:利用okhttp框架实现包含验证码的用户登录,保持session操作
cookie相关博客:OkHttp3的基本用法
创建一个工具类 OkHttpManager
初始化方法
/** * OkHttpManager */ public OkHttpManager(Context context) { //初始化OkHttpClient mOkHttpClient = new OkHttpClient().newBuilder().cookieJar(new CookieJar() { @Override public void saveFromResponse(HttpUrl httpUrl, List<Cookie> list) { cookieStore.put(httpUrl.host(), list); } @Override public List<Cookie> loadForRequest(HttpUrl httpUrl) { List<Cookie> cookies = cookieStore.get(httpUrl.host()); return cookies != null ? cookies : new ArrayList<Cookie>(); } })//设置Cookie管理 .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间 .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间 .writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间 .build(); //初始化Handler okHttpHandler = new Handler(context.getMainLooper()); }
单例模式
/** * 单例模式 * * @return */ public static OkHttpManager getInstance(Context context) { OkHttpManager inst = mInstance; if (inst == null) { synchronized (OkHttpManager.class) { inst = mInstance; if (inst == null) { inst = new OkHttpManager(context.getApplicationContext()); mInstance = inst; } } } return inst; }
异步请求
/** * okHttp异步请求 * * @param actionUrl * @param requestType * @param paramsMap * @param callBack * @param <T> * @return */ public <T> Call onRequestAsyn(String actionUrl, String requestType , HashMap<String, String> paramsMap, final ReqCallBack<T> callBack) { Request request = RequestBuilder(actionUrl, requestType, paramsMap); Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { failedCallBack(HTTP_REQUEST_FAILURE_MSG, callBack); Log.e(TAG, e.toString()); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String string = response.body().string(); Log.e(TAG, "response ----->" + string); successCallBack((T) string, callBack); } else { failedCallBack(HTTP_RESPONSE_FAILURE_MSG, callBack); } } }); return call; }
HTTP请求构建
/** * http请求构建 * @param actionUrl * @param requestType * @param paramsMap * @return */ private Request RequestBuilder(String actionUrl, String requestType , HashMap<String, String> paramsMap) { String baseUrl = EnergyApp.getInstance().getUrl(); if (requestType.equals(HttpRequestType.GET.toString())) {//GET请求 String requestUrl = String.format("%s/%s?%s", baseUrl, actionUrl, RequestParams(paramsMap).toString()); return RequestHeader().url(requestUrl).build(); } else if (requestType.equals(HttpRequestType.POST_JSON.toString())) {//POST JSON请求 RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, RequestParams(paramsMap).toString()); String requestUrl = String.format("%s/%s", baseUrl, actionUrl); return RequestHeader().url(requestUrl).post(body).build(); } else if (requestType.equals(HttpRequestType.POST_FORM.toString())) {//POST FORM请求 RequestBody formBody = RequestFormBody(paramsMap); String requestUrl = String.format("%s/%s", baseUrl, actionUrl); return RequestHeader().url(requestUrl).post(formBody).build(); } return null; }
为请求添加头信息
/** * 为请求添加头信息 * * @return */ private Request.Builder RequestHeader() { Request.Builder builder = new Request.Builder() .addHeader("Connection", "keep-alive") // .addHeader("platform", "2") .addHeader("phoneModel", Build.MODEL) .addHeader("systemVersion", Build.VERSION.RELEASE); // .addHeader("appVersion", "3.2.0"); return builder; }
字符参数组合
/** * 参数字符串 * * @return */ private StringBuilder RequestParams(HashMap<String, String> paramsMap) { StringBuilder tempParams = new StringBuilder(); try { int position = 0; for (String key : paramsMap.keySet()) { if (position > 0) { tempParams.append("&"); } tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); position++; } } catch (Exception e) { Log.e(TAG, e.toString()); } return tempParams; }
RequestBody参数组合
/** * 参数RequestBody * * @return */ private RequestBody RequestFormBody(HashMap<String, String> paramsMap) { FormBody.Builder builder = new FormBody.Builder(); for (String key : paramsMap.keySet()) { builder.add(key, paramsMap.get(key)); } return builder.build(); }
回调接口
public interface ReqCallBack<T> { /** * 响应成功 */ void onReqSuccess(T result); /** * 响应失败 */ void onReqFailed(String errorMsg); }
回调方法
/** * 处理成功信息 * * @param result * @param callBack * @param <T> */ private <T> void successCallBack(final T result, final ReqCallBack<T> callBack) { okHttpHandler.post(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onReqSuccess(result); } } }); } /** * 处理失败信息 * * @param errorMsg * @param callBack * @param <T> */ private <T> void failedCallBack(final String errorMsg, final ReqCallBack<T> callBack) { okHttpHandler.post(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onReqFailed(errorMsg); } } }); }
最后附上类声明变量
private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); private static final String TAG = OkHttpManager.class.getSimpleName(); private static volatile OkHttpManager mInstance;//单利引用 private OkHttpClient mOkHttpClient;//okHttpClient 实例 private Handler okHttpHandler;//全局处理子线程和M主线程通信 private static final String HTTP_REQUEST_FAILURE_MSG = "访问失败"; private static final String HTTP_RESPONSE_FAILURE_MSG = "服务器错误"; private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
结尾附上原博客组合源码,内容较多,点击+号打开查看:
注:源码中类MD5与变量upload_head未知
1 package com.zyp.energy.manager; 2 3 import android.content.Context; 4 import android.os.Build; 5 import android.os.Handler; 6 import android.util.Log; 7 8 import java.io.File; 9 import java.io.FileOutputStream; 10 import java.io.IOException; 11 import java.io.InputStream; 12 import java.net.URLEncoder; 13 import java.util.HashMap; 14 import java.util.concurrent.TimeUnit; 15 16 import okhttp3.Call; 17 import okhttp3.Callback; 18 import okhttp3.FormBody; 19 import okhttp3.MediaType; 20 import okhttp3.MultipartBody; 21 import okhttp3.OkHttpClient; 22 import okhttp3.Request; 23 import okhttp3.RequestBody; 24 import okhttp3.Response; 25 import okio.Buffer; 26 import okio.BufferedSink; 27 import okio.Okio; 28 import okio.Source; 29 30 public class OkHttpManager { 31 private static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"); 32 private static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8"); 33 private static final MediaType MEDIA_OBJECT_STREAM = MediaType.parse("application/octet-stream"); 34 private static final String TAG = OkHttpManager.class.getSimpleName(); 35 private static final String BASE_URL = "http://xxx.com/openapi";//请求接口根地址 36 private static volatile OkHttpManager mInstance;//单例模式 37 public static final int TYPE_GET = 0;//get请求 38 public static final int TYPE_POST_JSON = 1;//post请求参数为json 39 public static final int TYPE_POST_FORM = 2;//post请求参数为表单 40 private OkHttpClient mOkHttpClient;//okHttpClient 实例 41 private Handler okHttpHandler;//全局处理子线程和M主线程通信 42 43 /** 44 * 初始化RequestManager 45 */ 46 public OkHttpManager(Context context) { 47 //初始化OkHttpClient 48 mOkHttpClient = new OkHttpClient().newBuilder() 49 .connectTimeout(10, TimeUnit.SECONDS)//设置超时时间 50 .readTimeout(10, TimeUnit.SECONDS)//设置读取超时时间 51 .writeTimeout(10, TimeUnit.SECONDS)//设置写入超时时间 52 .build(); 53 //初始化Handler 54 okHttpHandler = new Handler(context.getMainLooper()); 55 } 56 57 /** 58 * 获取单例引用 59 * 60 * @return 61 */ 62 public static OkHttpManager getInstance(Context context) { 63 OkHttpManager inst = mInstance; 64 if (inst == null) { 65 synchronized (OkHttpManager.class) { 66 inst = mInstance; 67 if (inst == null) { 68 inst = new OkHttpManager(context.getApplicationContext()); 69 mInstance = inst; 70 } 71 } 72 } 73 return inst; 74 } 75 76 /** 77 * okHttp同步请求统一入口 78 * 79 * @param actionUrl 接口地址 80 * @param requestType 请求类型 81 * @param paramsMap 请求参数 82 */ 83 public void requestSyn(String actionUrl, int requestType, HashMap<String, String> paramsMap) { 84 switch (requestType) { 85 case TYPE_GET: 86 requestGetBySyn(actionUrl, paramsMap); 87 break; 88 case TYPE_POST_JSON: 89 requestPostBySyn(actionUrl, paramsMap); 90 break; 91 case TYPE_POST_FORM: 92 requestPostBySynWithForm(actionUrl, paramsMap); 93 break; 94 } 95 } 96 97 /** 98 * okHttp get同步请求 99 * 100 * @param actionUrl 接口地址 101 * @param paramsMap 请求参数 102 */ 103 private void requestGetBySyn(String actionUrl, HashMap<String, String> paramsMap) { 104 StringBuilder tempParams = new StringBuilder(); 105 try { 106 //处理参数 107 int pos = 0; 108 for (String key : paramsMap.keySet()) { 109 if (pos > 0) { 110 tempParams.append("&"); 111 } 112 //对参数进行URLEncoder 113 tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); 114 pos++; 115 } 116 //补全请求地址 117 String requestUrl = String.format("%s/%s?%s", BASE_URL, actionUrl, tempParams.toString()); 118 //创建一个请求 119 Request request = addHeaders().url(requestUrl).build(); 120 //创建一个Call 121 final Call call = mOkHttpClient.newCall(request); 122 //执行请求 123 final Response response = call.execute(); 124 response.body().string(); 125 } catch (Exception e) { 126 Log.e(TAG, e.toString()); 127 } 128 } 129 130 /** 131 * okHttp post同步请求 132 * 133 * @param actionUrl 接口地址 134 * @param paramsMap 请求参数 135 */ 136 private void requestPostBySyn(String actionUrl, HashMap<String, String> paramsMap) { 137 try { 138 //处理参数 139 StringBuilder tempParams = new StringBuilder(); 140 int pos = 0; 141 for (String key : paramsMap.keySet()) { 142 if (pos > 0) { 143 tempParams.append("&"); 144 } 145 tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); 146 pos++; 147 } 148 //补全请求地址 149 String requestUrl = String.format("%s/%s", BASE_URL, actionUrl); 150 //生成参数 151 String params = tempParams.toString(); 152 //创建一个请求实体对象 RequestBody 153 RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params); 154 //创建一个请求 155 final Request request = addHeaders().url(requestUrl).post(body).build(); 156 //创建一个Call 157 final Call call = mOkHttpClient.newCall(request); 158 //执行请求 159 Response response = call.execute(); 160 //请求执行成功 161 if (response.isSuccessful()) { 162 //获取返回数据 可以是String,bytes ,byteStream 163 Log.e(TAG, "response ----->" + response.body().string()); 164 } 165 } catch (Exception e) { 166 Log.e(TAG, e.toString()); 167 } 168 } 169 170 /** 171 * okHttp post同步请求表单提交 172 * 173 * @param actionUrl 接口地址 174 * @param paramsMap 请求参数 175 */ 176 private void requestPostBySynWithForm(String actionUrl, HashMap<String, String> paramsMap) { 177 try { 178 //创建一个FormBody.Builder 179 FormBody.Builder builder = new FormBody.Builder(); 180 for (String key : paramsMap.keySet()) { 181 //追加表单信息 182 builder.add(key, paramsMap.get(key)); 183 } 184 //生成表单实体对象 185 RequestBody formBody = builder.build(); 186 //补全请求地址 187 String requestUrl = String.format("%s/%s", BASE_URL, actionUrl); 188 //创建一个请求 189 final Request request = addHeaders().url(requestUrl).post(formBody).build(); 190 //创建一个Call 191 final Call call = mOkHttpClient.newCall(request); 192 //执行请求 193 Response response = call.execute(); 194 if (response.isSuccessful()) { 195 Log.e(TAG, "response ----->" + response.body().string()); 196 } 197 } catch (Exception e) { 198 Log.e(TAG, e.toString()); 199 } 200 } 201 202 /** 203 * okHttp异步请求统一入口 204 * 205 * @param actionUrl 接口地址 206 * @param requestType 请求类型 207 * @param paramsMap 请求参数 208 * @param callBack 请求返回数据回调 209 * @param <T> 数据泛型 210 **/ 211 public <T> Call requestAsyn(String actionUrl, int requestType, HashMap<String, String> paramsMap, ReqCallBack<T> callBack) { 212 Call call = null; 213 switch (requestType) { 214 case TYPE_GET: 215 call = requestGetByAsyn(actionUrl, paramsMap, callBack); 216 break; 217 case TYPE_POST_JSON: 218 call = requestPostByAsyn(actionUrl, paramsMap, callBack); 219 break; 220 case TYPE_POST_FORM: 221 call = requestPostByAsynWithForm(actionUrl, paramsMap, callBack); 222 break; 223 } 224 return call; 225 } 226 227 /** 228 * okHttp get异步请求 229 * 230 * @param actionUrl 接口地址 231 * @param paramsMap 请求参数 232 * @param callBack 请求返回数据回调 233 * @param <T> 数据泛型 234 * @return 235 */ 236 private <T> Call requestGetByAsyn(String actionUrl, HashMap<String, String> paramsMap, final ReqCallBack<T> callBack) { 237 StringBuilder tempParams = new StringBuilder(); 238 try { 239 int pos = 0; 240 for (String key : paramsMap.keySet()) { 241 if (pos > 0) { 242 tempParams.append("&"); 243 } 244 tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); 245 pos++; 246 } 247 String requestUrl = String.format("%s/%s?%s", BASE_URL, actionUrl, tempParams.toString()); 248 final Request request = addHeaders().url(requestUrl).build(); 249 final Call call = mOkHttpClient.newCall(request); 250 call.enqueue(new Callback() { 251 @Override 252 public void onFailure(Call call, IOException e) { 253 failedCallBack("访问失败", callBack); 254 Log.e(TAG, e.toString()); 255 } 256 257 @Override 258 public void onResponse(Call call, Response response) throws IOException { 259 if (response.isSuccessful()) { 260 String string = response.body().string(); 261 Log.e(TAG, "response ----->" + string); 262 successCallBack((T) string, callBack); 263 } else { 264 failedCallBack("服务器错误", callBack); 265 } 266 } 267 }); 268 return call; 269 } catch (Exception e) { 270 Log.e(TAG, e.toString()); 271 } 272 return null; 273 } 274 275 /** 276 * okHttp post异步请求 277 * 278 * @param actionUrl 接口地址 279 * @param paramsMap 请求参数 280 * @param callBack 请求返回数据回调 281 * @param <T> 数据泛型 282 * @return 283 */ 284 private <T> Call requestPostByAsyn(String actionUrl, HashMap<String, String> paramsMap, final ReqCallBack<T> callBack) { 285 try { 286 StringBuilder tempParams = new StringBuilder(); 287 int pos = 0; 288 for (String key : paramsMap.keySet()) { 289 if (pos > 0) { 290 tempParams.append("&"); 291 } 292 tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get(key), "utf-8"))); 293 pos++; 294 } 295 String params = tempParams.toString(); 296 RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params); 297 String requestUrl = String.format("%s/%s", BASE_URL, actionUrl); 298 final Request request = addHeaders().url(requestUrl).post(body).build(); 299 final Call call = mOkHttpClient.newCall(request); 300 call.enqueue(new Callback() { 301 @Override 302 public void onFailure(Call call, IOException e) { 303 failedCallBack("访问失败", callBack); 304 Log.e(TAG, e.toString()); 305 } 306 307 @Override 308 public void onResponse(Call call, Response response) throws IOException { 309 if (response.isSuccessful()) { 310 String string = response.body().string(); 311 Log.e(TAG, "response ----->" + string); 312 successCallBack((T) string, callBack); 313 } else { 314 failedCallBack("服务器错误", callBack); 315 } 316 } 317 }); 318 return call; 319 } catch (Exception e) { 320 Log.e(TAG, e.toString()); 321 } 322 return null; 323 } 324 325 /** 326 * okHttp post异步请求表单提交 327 * 328 * @param actionUrl 接口地址 329 * @param paramsMap 请求参数 330 * @param callBack 请求返回数据回调 331 * @param <T> 数据泛型 332 * @return 333 */ 334 private <T> Call requestPostByAsynWithForm(String actionUrl, HashMap<String, String> paramsMap, final ReqCallBack<T> callBack) { 335 try { 336 FormBody.Builder builder = new FormBody.Builder(); 337 for (String key : paramsMap.keySet()) { 338 builder.add(key, paramsMap.get(key)); 339 } 340 RequestBody formBody = builder.build(); 341 String requestUrl = String.format("%s/%s", BASE_URL, actionUrl); 342 final Request request = addHeaders().url(requestUrl).post(formBody).build(); 343 final Call call = mOkHttpClient.newCall(request); 344 call.enqueue(new Callback() { 345 @Override 346 public void onFailure(Call call, IOException e) { 347 failedCallBack("访问失败", callBack); 348 Log.e(TAG, e.toString()); 349 } 350 351 @Override 352 public void onResponse(Call call, Response response) throws IOException { 353 if (response.isSuccessful()) { 354 String string = response.body().string(); 355 Log.e(TAG, "response ----->" + string); 356 successCallBack((T) string, callBack); 357 } else { 358 failedCallBack("服务器错误", callBack); 359 } 360 } 361 }); 362 return call; 363 } catch (Exception e) { 364 Log.e(TAG, e.toString()); 365 } 366 return null; 367 } 368 369 public interface ReqCallBack<T> { 370 /** 371 * 响应成功 372 */ 373 void onReqSuccess(T result); 374 375 /** 376 * 响应失败 377 */ 378 void onReqFailed(String errorMsg); 379 } 380 381 /** 382 * 统一为请求添加头信息 383 * 384 * @return 385 */ 386 private Request.Builder addHeaders() { 387 Request.Builder builder = new Request.Builder() 388 .addHeader("Connection", "keep-alive") 389 .addHeader("platform", "2") 390 .addHeader("phoneModel", Build.MODEL) 391 .addHeader("systemVersion", Build.VERSION.RELEASE) 392 .addHeader("appVersion", "3.2.0"); 393 return builder; 394 } 395 396 /** 397 * 统一处理成功信息 398 * 399 * @param result 400 * @param callBack 401 * @param <T> 402 */ 403 private <T> void successCallBack(final T result, final ReqCallBack<T> callBack) { 404 okHttpHandler.post(new Runnable() { 405 @Override 406 public void run() { 407 if (callBack != null) { 408 callBack.onReqSuccess(result); 409 } 410 } 411 }); 412 } 413 414 /** 415 * 统一处理失败信息 416 * 417 * @param errorMsg 418 * @param callBack 419 * @param <T> 420 */ 421 private <T> void failedCallBack(final String errorMsg, final ReqCallBack<T> callBack) { 422 okHttpHandler.post(new Runnable() { 423 @Override 424 public void run() { 425 if (callBack != null) { 426 callBack.onReqFailed(errorMsg); 427 } 428 } 429 }); 430 } 431 /** 432 * 上传文件 433 * @param actionUrl 接口地址 434 * @param filePath 本地文件地址 435 */ 436 public <T> void upLoadFile(String actionUrl, String filePath, final ReqCallBack<T> callBack) { 437 //补全请求地址 438 String requestUrl = String.format("%s/%s", BASE_URL, actionUrl); 439 //创建File 440 File file = new File(filePath); 441 //创建RequestBody 442 RequestBody body = RequestBody.create(MEDIA_OBJECT_STREAM, file); 443 //创建Request 444 final Request request = new Request.Builder().url(requestUrl).post(body).build(); 445 final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); 446 call.enqueue(new Callback() { 447 @Override 448 public void onFailure(Call call, IOException e) { 449 Log.e(TAG, e.toString()); 450 failedCallBack("上传失败", callBack); 451 } 452 453 @Override 454 public void onResponse(Call call, Response response) throws IOException { 455 if (response.isSuccessful()) { 456 String string = response.body().string(); 457 Log.e(TAG, "response ----->" + string); 458 successCallBack((T) string, callBack); 459 } else { 460 failedCallBack("上传失败", callBack); 461 } 462 } 463 }); 464 } 465 /** 466 *上传文件 467 * @param actionUrl 接口地址 468 * @param paramsMap 参数 469 * @param callBack 回调 470 * @param <T> 471 */ 472 public <T>void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqCallBack<T> callBack) { 473 try { 474 //补全请求地址 475 String requestUrl = String.format("%s/%s", upload_head, actionUrl); 476 MultipartBody.Builder builder = new MultipartBody.Builder(); 477 //设置类型 478 builder.setType(MultipartBody.FORM); 479 //追加参数 480 for (String key : paramsMap.keySet()) { 481 Object object = paramsMap.get(key); 482 if (!(object instanceof File)) { 483 builder.addFormDataPart(key, object.toString()); 484 } else { 485 File file = (File) object; 486 builder.addFormDataPart(key, file.getName(), RequestBody.create(null, file)); 487 } 488 } 489 //创建RequestBody 490 RequestBody body = builder.build(); 491 //创建Request 492 final Request request = new Request.Builder().url(requestUrl).post(body).build(); 493 //单独设置参数 比如读取超时时间 494 final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); 495 call.enqueue(new Callback() { 496 @Override 497 public void onFailure(Call call, IOException e) { 498 Log.e(TAG, e.toString()); 499 failedCallBack("上传失败", callBack); 500 } 501 502 @Override 503 public void onResponse(Call call, Response response) throws IOException { 504 if (response.isSuccessful()) { 505 String string = response.body().string(); 506 Log.e(TAG, "response ----->" + string); 507 successCallBack((T) string, callBack); 508 } else { 509 failedCallBack("上传失败", callBack); 510 } 511 } 512 }); 513 } catch (Exception e) { 514 Log.e(TAG, e.toString()); 515 } 516 } 517 /** 518 *上传文件 519 * @param actionUrl 接口地址 520 * @param paramsMap 参数 521 * @param callBack 回调 522 * @param <T> 523 */ 524 public <T> void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqProgressCallBack<T> callBack) { 525 try { 526 //补全请求地址 527 String requestUrl = String.format("%s/%s", upload_head, actionUrl); 528 MultipartBody.Builder builder = new MultipartBody.Builder(); 529 //设置类型 530 builder.setType(MultipartBody.FORM); 531 //追加参数 532 for (String key : paramsMap.keySet()) { 533 Object object = paramsMap.get(key); 534 if (!(object instanceof File)) { 535 builder.addFormDataPart(key, object.toString()); 536 } else { 537 File file = (File) object; 538 builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callBack)); 539 } 540 } 541 //创建RequestBody 542 RequestBody body = builder.build(); 543 //创建Request 544 final Request request = new Request.Builder().url(requestUrl).post(body).build(); 545 final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); 546 call.enqueue(new Callback() { 547 @Override 548 public void onFailure(Call call, IOException e) { 549 Log.e(TAG, e.toString()); 550 failedCallBack("上传失败", callBack); 551 } 552 553 @Override 554 public void onResponse(Call call, Response response) throws IOException { 555 if (response.isSuccessful()) { 556 String string = response.body().string(); 557 Log.e(TAG, "response ----->" + string); 558 successCallBack((T) string, callBack); 559 } else { 560 failedCallBack("上传失败", callBack); 561 } 562 } 563 }); 564 } catch (Exception e) { 565 Log.e(TAG, e.toString()); 566 } 567 } 568 /** 569 * 创建带进度的RequestBody 570 * @param contentType MediaType 571 * @param file 准备上传的文件 572 * @param callBack 回调 573 * @param <T> 574 * @return 575 */ 576 public <T> RequestBody createProgressRequestBody(final MediaType contentType, final File file, final ReqProgressCallBack<T> callBack) { 577 return new RequestBody() { 578 @Override 579 public MediaType contentType() { 580 return contentType; 581 } 582 583 @Override 584 public long contentLength() { 585 return file.length(); 586 } 587 588 @Override 589 public void writeTo(BufferedSink sink) throws IOException { 590 Source source; 591 try { 592 source = Okio.source(file); 593 Buffer buf = new Buffer(); 594 long remaining = contentLength(); 595 long current = 0; 596 for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) { 597 sink.write(buf, readCount); 598 current += readCount; 599 Log.e(TAG, "current------>" + current); 600 progressCallBack(remaining, current, callBack); 601 } 602 } catch (Exception e) { 603 e.printStackTrace(); 604 } 605 } 606 }; 607 } 608 /** 609 * 下载文件 610 * @param fileUrl 文件url 611 * @param destFileDir 存储目标目录 612 */ 613 public <T> void downLoadFile(String fileUrl, final String destFileDir, final ReqCallBack<T> callBack) { 614 final String fileName = MD5.encode(fileUrl); 615 final File file = new File(destFileDir, fileName); 616 if (file.exists()) { 617 successCallBack((T) file, callBack); 618 return; 619 } 620 final Request request = new Request.Builder().url(fileUrl).build(); 621 final Call call = mOkHttpClient.newCall(request); 622 call.enqueue(new Callback() { 623 @Override 624 public void onFailure(Call call, IOException e) { 625 Log.e(TAG, e.toString()); 626 failedCallBack("下载失败", callBack); 627 } 628 629 @Override 630 public void onResponse(Call call, Response response) throws IOException { 631 InputStream is = null; 632 byte[] buf = new byte[2048]; 633 int len = 0; 634 FileOutputStream fos = null; 635 try { 636 long total = response.body().contentLength(); 637 Log.e(TAG, "total------>" + total); 638 long current = 0; 639 is = response.body().byteStream(); 640 fos = new FileOutputStream(file); 641 while ((len = is.read(buf)) != -1) { 642 current += len; 643 fos.write(buf, 0, len); 644 Log.e(TAG, "current------>" + current); 645 } 646 fos.flush(); 647 successCallBack((T) file, callBack); 648 } catch (IOException e) { 649 Log.e(TAG, e.toString()); 650 failedCallBack("下载失败", callBack); 651 } finally { 652 try { 653 if (is != null) { 654 is.close(); 655 } 656 if (fos != null) { 657 fos.close(); 658 } 659 } catch (IOException e) { 660 Log.e(TAG, e.toString()); 661 } 662 } 663 } 664 }); 665 } 666 /** 667 * 下载文件 668 * @param fileUrl 文件url 669 * @param destFileDir 存储目标目录 670 */ 671 public <T> void downLoadFile(String fileUrl, final String destFileDir, final ReqProgressCallBack<T> callBack) { 672 final String fileName = MD5.encode(fileUrl); 673 final File file = new File(destFileDir, fileName); 674 if (file.exists()) { 675 successCallBack((T) file, callBack); 676 return; 677 } 678 final Request request = new Request.Builder().url(fileUrl).build(); 679 final Call call = mOkHttpClient.newCall(request); 680 call.enqueue(new Callback() { 681 @Override 682 public void onFailure(Call call, IOException e) { 683 Log.e(TAG, e.toString()); 684 failedCallBack("下载失败", callBack); 685 } 686 687 @Override 688 public void onResponse(Call call, Response response) throws IOException { 689 InputStream is = null; 690 byte[] buf = new byte[2048]; 691 int len = 0; 692 FileOutputStream fos = null; 693 try { 694 long total = response.body().contentLength(); 695 Log.e(TAG, "total------>" + total); 696 long current = 0; 697 is = response.body().byteStream(); 698 fos = new FileOutputStream(file); 699 while ((len = is.read(buf)) != -1) { 700 current += len; 701 fos.write(buf, 0, len); 702 Log.e(TAG, "current------>" + current); 703 progressCallBack(total, current, callBack); 704 } 705 fos.flush(); 706 successCallBack((T) file, callBack); 707 } catch (IOException e) { 708 Log.e(TAG, e.toString()); 709 failedCallBack("下载失败", callBack); 710 } finally { 711 try { 712 if (is != null) { 713 is.close(); 714 } 715 if (fos != null) { 716 fos.close(); 717 } 718 } catch (IOException e) { 719 Log.e(TAG, e.toString()); 720 } 721 } 722 } 723 }); 724 } 725 public interface ReqProgressCallBack<T> extends ReqCallBack<T>{ 726 /** 727 * 响应进度更新 728 */ 729 void onProgress(long total, long current); 730 } 731 /** 732 * 统一处理进度信息 733 * @param total 总计大小 734 * @param current 当前进度 735 * @param callBack 736 * @param <T> 737 */ 738 private <T> void progressCallBack(final long total, final long current, final ReqProgressCallBack<T> callBack) { 739 okHttpHandler.post(new Runnable() { 740 @Override 741 public void run() { 742 if (callBack != null) { 743 callBack.onProgress(total, current); 744 } 745 } 746 }); 747 } 748 }
标签:looper 请求 声明 public header 管理 body sink code
原文地址:http://www.cnblogs.com/bmbh/p/7095463.html