前面介紹了基於okHttp的get、post基本使用(http://www.cnblogs.com/whoislcj/p/5526431.html),今天來實現一下基於okHttp的文件上傳、下載。html
okHttp相關文章地址:java
/** * 上傳文件 * @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); } } }); }
/** *上傳文件 * @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()); } }
/** *上傳文件 * @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()); } }
/** * 建立帶進度的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(); } } }; }
/** * 下載文件 * @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()); } } } }); }
/** * 下載文件 * @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()); } } } }); }
public interface ReqProgressCallBack<T> extends ReqCallBack<T>{ /** * 響應進度更新 */ void onProgress(long total, long current); }
/** * 統一處理進度信息 * @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的文件上傳、下載基本實現,接下來就是返回數據的解析了。緩存