Parcourir la source

Fix download did not return a problem.

yanyi il y a 6 ans
Parent
commit
5291190564

+ 1 - 1
README.md

@@ -27,4 +27,4 @@ module 下添加
     compile 'com.yanyi.benyanyi:okhttplib:1.0.7'
     
 ### 更新记录
-* 2018/09/12(1.0.7) 修复下载文件回调没返回问题
+* 2018/09/12(1.0.7) 修复下载文件回调没返回问题,下载路径都是根目录下

+ 2 - 2
app/src/main/java/com/mylove/okhttp/MainActivity.java

@@ -43,10 +43,10 @@ public class MainActivity extends AppCompatActivity {
     private void init() {
         OkHttpInfo.soapDataTopString = "";
         JLog.init(true);
-        String url = "http://www.yanyi.red/bluetooth/dfu_pkg0904.zip";
+        String url = "http://www.yanyi.red/bluetooth/ios.pdf";
         String filePath = "/dectector/dfu/";
 //        String filePath = Environment.getExternalStorageDirectory().toString() + "/dectector/dfu/";
-        OkHttpUtil.getInstance(this).downloadFile(url).download(filePath, new OnDownloadListener() {
+        OkHttpUtil.getInstance(this).downloadFile(url).downloads(filePath, new OnDownloadListener() {
             @Override
             public void onDownloading(int progress) {
                 JLog.d(progress + "");

+ 2 - 44
okhttplib/src/main/java/com/mylove/okhttp/DownloadObservable.java

@@ -2,7 +2,6 @@ package com.mylove.okhttp;
 
 import android.annotation.SuppressLint;
 import android.content.Context;
-import android.os.Environment;
 import android.support.annotation.NonNull;
 
 import java.io.File;
@@ -115,25 +114,6 @@ class DownloadObservable {
                     .build();
             Call call = okHttpClient.newCall(request);
             sendCall(url, call, subscriber);
-//            sendCall(url, call, new onOkHttpListener() {
-//                @Override
-//                public void onCompleted() {
-//                    subscriber.onComplete();
-//                }
-//
-//                @Override
-//                public <T> void onSuccess(T message) {
-//                    DownloadBean bean1 = (DownloadBean) message;
-//                    LogHelper.v(bean1.toString());
-//                    subscriber.onNext(bean1);
-//                }
-//
-//                @Override
-//                public void onFailure(Throwable t) {
-//                    LogHelper.e(t.getMessage());
-//                    subscriber.onError(t);
-//                }
-//            });
         } else {
             subscriber.onError(new Exception(bean.getMsg()));
         }
@@ -161,11 +141,11 @@ class DownloadObservable {
                 int len = 0;
                 FileOutputStream fos = null;
                 // 储存下载文件的目录
-                String savePath = isExistDir(filePath);
+                String savePath = FileUtil.isExistDir(filePath);
                 try {
                     is = response.body().byteStream();
                     long total = response.body().contentLength();
-                    File file = new File(savePath, getNameFromUrl(url));
+                    File file = new File(savePath, FileUtil.getNameFromUrl(url));
                     bean.filePath = file.getAbsolutePath();
                     if (OkHttpInfo.isLOG)
                         LogHelper.d(filePath);
@@ -216,26 +196,4 @@ class DownloadObservable {
         });
     }
 
-    /**
-     * @param saveDir
-     * @return
-     * @throws IOException 判断下载目录是否存在
-     */
-    private String isExistDir(String saveDir) throws IOException {
-        // 下载位置
-        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
-        if (!downloadFile.mkdirs()) {
-            downloadFile.createNewFile();
-        }
-        return downloadFile.getAbsolutePath();
-    }
-
-    /**
-     * @param url
-     * @return 从下载连接中解析出文件名
-     */
-    @NonNull
-    private String getNameFromUrl(String url) {
-        return url.substring(url.lastIndexOf("/") + 1);
-    }
 }

+ 208 - 0
okhttplib/src/main/java/com/mylove/okhttp/DownloadObservables.java

@@ -0,0 +1,208 @@
+package com.mylove.okhttp;
+
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.support.annotation.NonNull;
+
+import org.reactivestreams.Subscriber;
+import org.reactivestreams.Subscription;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.concurrent.TimeUnit;
+
+import io.reactivex.BackpressureStrategy;
+import io.reactivex.Flowable;
+import io.reactivex.FlowableEmitter;
+import io.reactivex.FlowableOnSubscribe;
+import io.reactivex.android.schedulers.AndroidSchedulers;
+import io.reactivex.schedulers.Schedulers;
+import okhttp3.Call;
+import okhttp3.Callback;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+
+/**
+ * @author BenYanYi
+ * @date 2018/9/13 17:43
+ * @email ben@yanyi.red
+ * @overview
+ */
+public class DownloadObservables {
+    @SuppressLint("StaticFieldLeak")
+    private static DownloadObservables instance;
+    @SuppressLint("StaticFieldLeak")
+    private static Context mContext;
+    private String filePath;
+    private static OkHttpClient okHttpClient;
+
+    private DownloadObservables() {
+    }
+
+    static DownloadObservables getInstance(Context context) {
+        if (instance == null) {
+            synchronized (DownloadObservable.class) {
+                if (instance == null) {
+                    instance = new DownloadObservables();
+                    OkHttpClient httpClient = new OkHttpClient();
+                    okHttpClient = httpClient.newBuilder()
+                            .addNetworkInterceptor(new CacheInterceptor())
+                            .addInterceptor(Cache.HTTP_LOGGING_INTERCEPTOR)
+                            .cache(Cache.privateCache(context))
+                            .connectTimeout(30, TimeUnit.SECONDS)
+                            .readTimeout(30, TimeUnit.SECONDS)
+                            .build();
+                }
+            }
+        }
+        mContext = context;
+        return instance;
+    }
+
+    void request(String url, String filePath, final OnDownloadListener onDownloadListener) {
+        this.filePath = filePath;
+        getObservable(url)
+                .subscribeOn(Schedulers.io())
+                .observeOn(AndroidSchedulers.mainThread())
+//                .subscribeOn(Schedulers.newThread())
+//                .observeOn(Schedulers.newThread())
+                .subscribe(new Subscriber<DownloadBean>() {
+                    private Subscription mSubscription;
+
+                    @Override
+                    public void onSubscribe(Subscription s) {
+                        s.request(1);//设置初始请求数据量为1
+                        mSubscription = s;
+                    }
+
+                    @Override
+                    public void onNext(DownloadBean downloadBean) {
+                        if (OkHttpInfo.isLOG) {
+                            LogHelper.v(downloadBean);
+                        }
+                        if (downloadBean.status == 1) {
+                            onDownloadListener.onSuccess(downloadBean.filePath);
+                        } else {
+                            onDownloadListener.onDownloading(downloadBean.progress);
+                        }
+                        mSubscription.request(1);
+                    }
+
+                    @Override
+                    public void onError(Throwable t) {
+                        if (OkHttpInfo.isLOG)
+                            LogHelper.e(t.getMessage());
+                        onDownloadListener.onFailure(t);
+                    }
+
+                    @Override
+                    public void onComplete() {
+                        if (OkHttpInfo.isLOG)
+                            LogHelper.v("*****");
+                        onDownloadListener.onCompleted();
+                    }
+                });
+    }
+
+    private Flowable<DownloadBean> getObservable(final String url) {
+        return Flowable.create(new FlowableOnSubscribe<DownloadBean>() {
+            @Override
+            public void subscribe(FlowableEmitter<DownloadBean> e) throws Exception {
+                send(url, e);
+            }
+        }, BackpressureStrategy.MISSING);
+    }
+
+    private void send(final String url, FlowableEmitter<DownloadBean> subscriber) {
+        InternetBean bean = Internet.ifInternet(mContext);
+        if (bean.getStatus()) {
+            Request request = new Request.Builder()
+                    .url(url)
+                    .build();
+            Call call = okHttpClient.newCall(request);
+            sendCall(url, call, subscriber);
+        } else {
+            subscriber.onError(new Exception(bean.getMsg()));
+        }
+    }
+
+    /**
+     * 请求
+     */
+    private void sendCall(final String url, Call call, final FlowableEmitter<DownloadBean> subscriber) {
+
+        call.enqueue(new Callback() {
+            @Override
+            public void onFailure(@NonNull Call call, @NonNull IOException e) {
+                if (OkHttpInfo.isLOG)
+                    LogHelper.e(e.getMessage());
+                subscriber.onError(e);
+                subscriber.onComplete();
+            }
+
+            @Override
+            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
+                DownloadBean bean = new DownloadBean();
+                InputStream is = null;
+                byte[] buf = new byte[2048];
+                int len = 0;
+                FileOutputStream fos = null;
+                // 储存下载文件的目录
+                String savePath = FileUtil.isExistDir(filePath);
+                try {
+                    is = response.body().byteStream();
+                    long total = response.body().contentLength();
+                    File file = new File(savePath, FileUtil.getNameFromUrl(url));
+                    bean.filePath = file.getAbsolutePath();
+                    if (OkHttpInfo.isLOG)
+                        LogHelper.d(filePath);
+                    fos = new FileOutputStream(file);
+                    long sum = 0;
+                    while ((len = is.read(buf)) != -1) {
+                        fos.write(buf, 0, len);
+                        sum += len;
+                        int progress = (int) (sum * 1.0f / total * 100);
+                        if (OkHttpInfo.isLOG)
+                            LogHelper.i(progress + "%");
+                        bean.status = 0;
+                        bean.progress = progress;
+                        if (OkHttpInfo.isLOG)
+                            LogHelper.d(bean);
+                        // 下载中
+                        subscriber.onNext(bean);
+                    }
+                    fos.flush();
+                    // 下载完成
+                    bean.status = 1;
+                    if (OkHttpInfo.isLOG)
+                        LogHelper.d(bean);
+                    subscriber.onNext(bean);
+                    subscriber.onComplete();
+                } catch (Exception e) {
+                    if (OkHttpInfo.isLOG)
+                        LogHelper.e(e.getMessage());
+                    subscriber.onError(e);
+                    subscriber.onComplete();
+                } finally {
+                    try {
+                        if (is != null)
+                            is.close();
+                    } catch (IOException e) {
+                        if (OkHttpInfo.isLOG)
+                            LogHelper.e(e.getMessage());
+                    }
+                    try {
+                        if (fos != null)
+                            fos.close();
+                    } catch (IOException e) {
+                        if (OkHttpInfo.isLOG)
+                            LogHelper.e(e.getMessage());
+                    }
+                }
+            }
+        });
+    }
+}

+ 12 - 0
okhttplib/src/main/java/com/mylove/okhttp/DownloadRequest.java

@@ -38,4 +38,16 @@ public class DownloadRequest {
         }
         DownloadObservable.getInstance(mContext).request(url, filePath, onDownloadListener);
     }
+
+    /**
+     * @param filePath           储存下载文件的SDCard目录
+     * @param onDownloadListener 监听
+     */
+    public void downloads(String filePath, OnDownloadListener onDownloadListener) {
+        //saveDir判断不能为空
+        if (FormatUtil.isEmpty(filePath)) {
+            throw new NullPointerException("filePath is the SDCard directory of the downloaded file, cannot be empty.");
+        }
+        DownloadObservables.getInstance(mContext).request(url, filePath, onDownloadListener);
+    }
 }

+ 11 - 0
okhttplib/src/main/java/com/mylove/okhttp/FileUtil.java

@@ -2,6 +2,7 @@ package com.mylove.okhttp;
 
 import android.graphics.Bitmap;
 import android.os.Environment;
+import android.support.annotation.NonNull;
 
 import java.io.File;
 import java.io.FileOutputStream;
@@ -60,4 +61,14 @@ class FileUtil {
         }
         return sdDir.toString();
     }
+
+    /**
+     * @param url
+     * @return 从下载连接中解析出文件名
+     */
+    @NonNull
+    static String getNameFromUrl(String url) {
+        return url.substring(url.lastIndexOf("/") + 1);
+    }
+
 }

+ 3 - 17
okhttplib/src/main/java/com/mylove/okhttp/ObservableRequest.java

@@ -210,20 +210,6 @@ class ObservableRequest {
         });
     }
 
-    private Request request(String url, Map<Object, Object> map) {
-        FormBody.Builder builder = new FormBody.Builder();
-        if (FormatUtil.isMapNotEmpty(map)) {
-            for (Map.Entry<Object, Object> entry : map.entrySet()) {
-                builder.add(entry.getKey().toString(), entry.getValue().toString());
-            }
-        }
-        FormBody build = builder.build();
-        return new Request.Builder()
-                .url(url)
-                .post(build)
-                .build();
-    }
-
     /**
      * 判断请求方式
      *
@@ -236,8 +222,6 @@ class ObservableRequest {
             requestType = RequestType.POST;
         }
         switch (requestType) {
-            case GET:
-                return get(url, oMap);
             case POST_XML_SOAP:
                 return postXMLToSoap(url, oMap);
             case UP_FILE:
@@ -245,8 +229,10 @@ class ObservableRequest {
             case ALL:
                 return upAll(url, oMap);
             case POST:
-            default:
                 return post(url, oMap);
+            case GET:
+            default:
+                return get(url, oMap);
         }
     }