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