前言:
前面介紹了基於okHttp的get、post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天來實現一下基於okHttp的檔案上傳、下載。
okHttp相關文章地址:
- Android okHttp網路請求之Get/Post請求
- Android okHttp網路請求之檔案上傳下載
- Android okHttp網路請求之Json解析
- Android okHttp網路請求之快取控制Cache-Control
- Android okHttp網路請求之Retrofit+Okhttp組合
檔案上傳:
1.)不帶引數上傳檔案
/** * 上傳檔案 * @param actionUrl 介面地址 * @param filePath 本地檔案地址 */ public <T> void upLoadFile(String actionUrl, String filePath, final ReqCallBack<T> callBack) { //補全請求地址 String requestUrl = String.format("%s/%s", BASE_URL, actionUrl); //建立File File file = new File(filePath); //建立RequestBody RequestBody body = RequestBody.create(MEDIA_OBJECT_STREAM, file); //建立Request final Request request = new Request.Builder().url(requestUrl).post(body).build(); final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, e.toString()); failedCallBack("上傳失敗", callBack); } @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("上傳失敗", callBack); } } }); }
2.)帶引數上傳檔案
/** *上傳檔案 * @param actionUrl 介面地址 * @param paramsMap 引數 * @param callBack 回撥 * @param <T> */ public <T>void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqCallBack<T> callBack) { try { //補全請求地址 String requestUrl = String.format("%s/%s", upload_head, actionUrl); MultipartBody.Builder builder = new MultipartBody.Builder(); //設定型別 builder.setType(MultipartBody.FORM); //追加引數 for (String key : paramsMap.keySet()) { Object object = paramsMap.get(key); if (!(object instanceof File)) { builder.addFormDataPart(key, object.toString()); } else { File file = (File) object; builder.addFormDataPart(key, file.getName(), RequestBody.create(null, file)); } } //建立RequestBody RequestBody body = builder.build(); //建立Request final Request request = new Request.Builder().url(requestUrl).post(body).build(); //單獨設定引數 比如讀取超時時間 final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, e.toString()); failedCallBack("上傳失敗", callBack); } @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("上傳失敗", callBack); } } }); } catch (Exception e) { Log.e(TAG, e.toString()); } }
3.)帶引數帶進度上傳檔案
/** *上傳檔案 * @param actionUrl 介面地址 * @param paramsMap 引數 * @param callBack 回撥 * @param <T> */ public <T> void upLoadFile(String actionUrl, HashMap<String, Object> paramsMap, final ReqProgressCallBack<T> callBack) { try { //補全請求地址 String requestUrl = String.format("%s/%s", upload_head, actionUrl); MultipartBody.Builder builder = new MultipartBody.Builder(); //設定型別 builder.setType(MultipartBody.FORM); //追加引數 for (String key : paramsMap.keySet()) { Object object = paramsMap.get(key); if (!(object instanceof File)) { builder.addFormDataPart(key, object.toString()); } else { File file = (File) object; builder.addFormDataPart(key, file.getName(), createProgressRequestBody(MEDIA_OBJECT_STREAM, file, callBack)); } } //建立RequestBody RequestBody body = builder.build(); //建立Request final Request request = new Request.Builder().url(requestUrl).post(body).build(); final Call call = mOkHttpClient.newBuilder().writeTimeout(50, TimeUnit.SECONDS).build().newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, e.toString()); failedCallBack("上傳失敗", callBack); } @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("上傳失敗", callBack); } } }); } catch (Exception e) { Log.e(TAG, e.toString()); } }
4.)建立帶進度RequestBody
/** * 建立帶進度的RequestBody * @param contentType MediaType * @param file 準備上傳的檔案 * @param callBack 回撥 * @param <T> * @return */ public <T> RequestBody createProgressRequestBody(final MediaType contentType, final File file, final ReqProgressCallBack<T> callBack) { return new RequestBody() { @Override public MediaType contentType() { return contentType; } @Override public long contentLength() { return file.length(); } @Override public void writeTo(BufferedSink sink) throws IOException { Source source; try { source = Okio.source(file); Buffer buf = new Buffer(); long remaining = contentLength(); long current = 0; for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) { sink.write(buf, readCount); current += readCount; Log.e(TAG, "current------>" + current); progressCallBack(remaining, current, callBack); } } catch (Exception e) { e.printStackTrace(); } } }; }
5.)不帶進度檔案下載
/** * 下載檔案 * @param fileUrl 檔案url * @param destFileDir 儲存目標目錄 */ public <T> void downLoadFile(String fileUrl, final String destFileDir, final ReqCallBack<T> callBack) { final String fileName = MD5.encode(fileUrl); final File file = new File(destFileDir, fileName); if (file.exists()) { successCallBack((T) file, callBack); return; } final Request request = new Request.Builder().url(fileUrl).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, e.toString()); failedCallBack("下載失敗", callBack); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { long total = response.body().contentLength(); Log.e(TAG, "total------>" + total); long current = 0; is = response.body().byteStream(); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { current += len; fos.write(buf, 0, len); Log.e(TAG, "current------>" + current); } fos.flush(); successCallBack((T) file, callBack); } catch (IOException e) { Log.e(TAG, e.toString()); failedCallBack("下載失敗", callBack); } finally { try { if (is != null) { is.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { Log.e(TAG, e.toString()); } } } }); }
6.)帶進度檔案下載
/** * 下載檔案 * @param fileUrl 檔案url * @param destFileDir 儲存目標目錄 */ public <T> void downLoadFile(String fileUrl, final String destFileDir, final ReqProgressCallBack<T> callBack) { final String fileName = MD5.encode(fileUrl); final File file = new File(destFileDir, fileName); if (file.exists()) { successCallBack((T) file, callBack); return; } final Request request = new Request.Builder().url(fileUrl).build(); final Call call = mOkHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Log.e(TAG, e.toString()); failedCallBack("下載失敗", callBack); } @Override public void onResponse(Call call, Response response) throws IOException { InputStream is = null; byte[] buf = new byte[2048]; int len = 0; FileOutputStream fos = null; try { long total = response.body().contentLength(); Log.e(TAG, "total------>" + total); long current = 0; is = response.body().byteStream(); fos = new FileOutputStream(file); while ((len = is.read(buf)) != -1) { current += len; fos.write(buf, 0, len); Log.e(TAG, "current------>" + current); progressCallBack(total, current, callBack); } fos.flush(); successCallBack((T) file, callBack); } catch (IOException e) { Log.e(TAG, e.toString()); failedCallBack("下載失敗", callBack); } finally { try { if (is != null) { is.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { Log.e(TAG, e.toString()); } } } }); }
7.)介面ReqProgressCallBack.java實現
public interface ReqProgressCallBack<T> extends ReqCallBack<T>{ /** * 響應進度更新 */ void onProgress(long total, long current); }
8.)進度回撥實現
/** * 統一處理進度資訊 * @param total 總計大小 * @param current 當前進度 * @param callBack * @param <T> */ private <T> void progressCallBack(final long total, final long current, final ReqProgressCallBack<T> callBack) { okHttpHandler.post(new Runnable() { @Override public void run() { if (callBack != null) { callBack.onProgress(total, current); } } }); }
小結:基於okHttp的檔案上傳、下載基本實現,接下來就是返回資料的解析了。