DownloadObservable.java 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. package com.mylove.okhttp;
  2. import android.annotation.SuppressLint;
  3. import android.content.Context;
  4. import android.support.annotation.NonNull;
  5. import com.mylove.okhttp.listener.OnDownloadListener;
  6. import java.io.File;
  7. import java.io.FileOutputStream;
  8. import java.io.IOException;
  9. import java.io.InputStream;
  10. import java.util.concurrent.TimeUnit;
  11. import io.reactivex.Observable;
  12. import io.reactivex.ObservableEmitter;
  13. import io.reactivex.ObservableOnSubscribe;
  14. import io.reactivex.Observer;
  15. import io.reactivex.android.schedulers.AndroidSchedulers;
  16. import io.reactivex.disposables.Disposable;
  17. import io.reactivex.schedulers.Schedulers;
  18. import okhttp3.Call;
  19. import okhttp3.Callback;
  20. import okhttp3.OkHttpClient;
  21. import okhttp3.Request;
  22. import okhttp3.Response;
  23. /**
  24. * @author myLove
  25. */
  26. class DownloadObservable {
  27. @SuppressLint("StaticFieldLeak")
  28. private static DownloadObservable instance;
  29. @SuppressLint("StaticFieldLeak")
  30. private static Context mContext;
  31. private String filePath;
  32. private static OkHttpClient okHttpClient;
  33. private DownloadObservable() {
  34. }
  35. static DownloadObservable getInstance(Context context) {
  36. if (instance == null) {
  37. synchronized (DownloadObservable.class) {
  38. if (instance == null) {
  39. instance = new DownloadObservable();
  40. OkHttpClient httpClient = new OkHttpClient();
  41. okHttpClient = httpClient.newBuilder()
  42. .addNetworkInterceptor(new CacheInterceptor())
  43. .addInterceptor(Cache.HTTP_LOGGING_INTERCEPTOR)
  44. .cache(Cache.privateCache(context))
  45. .connectTimeout(30, TimeUnit.SECONDS)
  46. .readTimeout(30, TimeUnit.SECONDS)
  47. .writeTimeout(30, TimeUnit.SECONDS)
  48. .sslSocketFactory(SSLConfig.createSSLSocketFactory())//支持HTTPS请求,跳过证书验证
  49. .build();
  50. }
  51. }
  52. }
  53. mContext = context;
  54. return instance;
  55. }
  56. void request(String url, String filePath, final OnDownloadListener onDownloadListener) {
  57. this.filePath = filePath;
  58. getObservable(url)
  59. .subscribeOn(Schedulers.io())
  60. .observeOn(AndroidSchedulers.mainThread())
  61. .subscribe(new Observer<DownloadBean>() {
  62. @Override
  63. public void onSubscribe(Disposable d) {
  64. }
  65. @Override
  66. public void onNext(DownloadBean bean) {
  67. if (OkHttpInfo.isLOG) {
  68. LogHelper.v(bean);
  69. }
  70. if (bean.status == 1) {
  71. onDownloadListener.onSuccess(bean.filePath);
  72. } else {
  73. onDownloadListener.onDownloading(bean.progress);
  74. }
  75. }
  76. @Override
  77. public void onError(Throwable e) {
  78. if (OkHttpInfo.isLOG)
  79. LogHelper.e(e.getMessage());
  80. onDownloadListener.onFailure(e);
  81. }
  82. @Override
  83. public void onComplete() {
  84. if (OkHttpInfo.isLOG)
  85. LogHelper.v("*****");
  86. onDownloadListener.onCompleted();
  87. }
  88. });
  89. }
  90. private Observable<DownloadBean> getObservable(final String url) {
  91. return Observable.create(new ObservableOnSubscribe<DownloadBean>() {
  92. @Override
  93. public void subscribe(ObservableEmitter<DownloadBean> e) {
  94. send(url, e);
  95. }
  96. });
  97. }
  98. private void send(final String url, ObservableEmitter<DownloadBean> subscriber) {
  99. InternetBean bean = Internet.ifInternet(mContext);
  100. if (bean.getStatus()) {
  101. Request request = new Request.Builder()
  102. .url(url)
  103. .build();
  104. Call call = okHttpClient.newCall(request);
  105. sendCall(url, call, subscriber);
  106. } else {
  107. subscriber.onError(new Exception(bean.getMsg()));
  108. }
  109. }
  110. /**
  111. * 请求
  112. */
  113. private void sendCall(final String url, Call call, final ObservableEmitter<DownloadBean> subscriber) {
  114. call.enqueue(new Callback() {
  115. @Override
  116. public void onFailure(@NonNull Call call, @NonNull IOException e) {
  117. if (OkHttpInfo.isLOG)
  118. LogHelper.e(e.getMessage());
  119. subscriber.onError(e);
  120. subscriber.onComplete();
  121. }
  122. @Override
  123. public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
  124. DownloadBean bean = new DownloadBean();
  125. InputStream is = null;
  126. byte[] buf = new byte[2048];
  127. int len = 0;
  128. FileOutputStream fos = null;
  129. // 储存下载文件的目录
  130. String savePath = FileUtil.isExistDir(filePath);
  131. try {
  132. is = response.body().byteStream();
  133. long total = response.body().contentLength();
  134. File file = new File(savePath, FileUtil.getNameFromUrl(url));
  135. bean.filePath = file.getAbsolutePath();
  136. if (OkHttpInfo.isLOG)
  137. LogHelper.d(filePath);
  138. fos = new FileOutputStream(file);
  139. long sum = 0;
  140. while ((len = is.read(buf)) != -1) {
  141. fos.write(buf, 0, len);
  142. sum += len;
  143. int progress = (int) (sum * 1.0f / total * 100);
  144. if (OkHttpInfo.isLOG)
  145. LogHelper.i(progress + "%");
  146. bean.status = 0;
  147. bean.progress = progress;
  148. if (OkHttpInfo.isLOG)
  149. LogHelper.d(bean);
  150. // 下载中
  151. subscriber.onNext(bean);
  152. }
  153. fos.flush();
  154. // 下载完成
  155. bean.status = 1;
  156. if (OkHttpInfo.isLOG)
  157. LogHelper.d(bean);
  158. subscriber.onNext(bean);
  159. subscriber.onComplete();
  160. } catch (Exception e) {
  161. if (OkHttpInfo.isLOG)
  162. LogHelper.e(e.getMessage());
  163. subscriber.onError(e);
  164. subscriber.onComplete();
  165. } finally {
  166. try {
  167. if (is != null)
  168. is.close();
  169. } catch (IOException e) {
  170. if (OkHttpInfo.isLOG)
  171. LogHelper.e(e.getMessage());
  172. }
  173. try {
  174. if (fos != null)
  175. fos.close();
  176. } catch (IOException e) {
  177. if (OkHttpInfo.isLOG)
  178. LogHelper.e(e.getMessage());
  179. }
  180. }
  181. }
  182. });
  183. }
  184. }