Kaynağa Gözat

download url ip update

billyyoyo 6 yıl önce
ebeveyn
işleme
be29641cf9

+ 4 - 0
app/src/main/java/com/sheep/gamegroup/util/Md5Util.java

@@ -81,6 +81,7 @@ public class Md5Util {
         }
         }
         return calculatedDigest.equalsIgnoreCase(firstCalculatedDigest);
         return calculatedDigest.equalsIgnoreCase(firstCalculatedDigest);
     }
     }
+
     /**
     /**
      * 校验文件MD5码
      * 校验文件MD5码
      */
      */
@@ -125,6 +126,9 @@ public class Md5Util {
         } catch (FileNotFoundException e) {
         } catch (FileNotFoundException e) {
 //            ALog.e(TAG, e);
 //            ALog.e(TAG, e);
             return null;
             return null;
+        } catch (OutOfMemoryError err) {
+            err.printStackTrace();
+            return null;
         }
         }
 
 
         return getFileMD5(is);
         return getFileMD5(is);

+ 22 - 0
app/src/main/java/com/sheep/gamegroup/util/NetUtil.java

@@ -25,9 +25,12 @@ import android.util.Log;
 
 
 import com.sheep.jiuyan.samllsheep.SheepApp;
 import com.sheep.jiuyan.samllsheep.SheepApp;
 
 
+import java.lang.reflect.Field;
 import java.net.InetAddress;
 import java.net.InetAddress;
+import java.net.InetSocketAddress;
 import java.net.NetworkInterface;
 import java.net.NetworkInterface;
 import java.net.SocketException;
 import java.net.SocketException;
+import java.net.URLConnection;
 import java.util.Enumeration;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.HashMap;
 import java.util.List;
 import java.util.List;
@@ -322,4 +325,23 @@ public class NetUtil {
         status.put("LAC", lac);
         status.put("LAC", lac);
         status.put("CID", cid);
         status.put("CID", cid);
     }
     }
+
+    public static String getUrlIp(URLConnection conn){
+        try {
+            Field delegateField = conn.getClass().getDeclaredField("delegate");
+            delegateField.setAccessible(true);
+            Object delegate = delegateField.get(conn);
+            Field routeField = delegate.getClass().getDeclaredField("route");
+            routeField.setAccessible(true);
+            Object route = routeField.get(delegate);
+            Field inetField = route.getClass().getDeclaredField("inetSocketAddress");
+            inetField.setAccessible(true);
+            InetSocketAddress address = (InetSocketAddress) inetField.get(route);
+            String ip = address.getAddress().getHostAddress();
+            return ip;
+        } catch (Exception e) {
+            e.printStackTrace();
+            return "0.0.0.0";
+        }
+    }
 }
 }

+ 314 - 0
app/src/main/java/com/sheep/gamegroup/util/SheepDownloadConnection.java

@@ -0,0 +1,314 @@
+/*
+ * Copyright (c) 2017 LingoChamp Inc.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.sheep.gamegroup.util;
+
+import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
+
+import com.liulishuo.okdownload.IRedirectHandler;
+import com.liulishuo.okdownload.OkDownload;
+import com.liulishuo.okdownload.RedirectUtil;
+import com.liulishuo.okdownload.core.Util;
+import com.liulishuo.okdownload.core.connection.DownloadConnection;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.ProtocolException;
+import java.net.Proxy;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class SheepDownloadConnection implements DownloadConnection, DownloadConnection.Connected {
+
+    protected URLConnection connection;
+    private Configuration configuration;
+    private URL url;
+    private IRedirectHandler redirectHandler;
+
+    private static final String TAG = "SheepDownloadConnection";
+
+    SheepDownloadConnection(URLConnection connection) {
+        this(connection, new RedirectHandler());
+    }
+
+    SheepDownloadConnection(URLConnection connection, IRedirectHandler redirectHandler) {
+        this.connection = connection;
+        this.url = connection.getURL();
+        this.redirectHandler = redirectHandler;
+    }
+
+    public SheepDownloadConnection(String originUrl, Configuration configuration) throws IOException {
+        this(new URL(originUrl), configuration);
+    }
+
+    public SheepDownloadConnection(URL url, Configuration configuration) throws IOException {
+        this(url, configuration, new RedirectHandler());
+    }
+
+    public SheepDownloadConnection(
+            URL url,
+            Configuration configuration,
+            IRedirectHandler redirectHandler) throws IOException {
+        this.configuration = configuration;
+        this.url = url;
+        this.redirectHandler = redirectHandler;
+        configUrlConnection();
+    }
+
+    public SheepDownloadConnection(String originUrl) throws IOException {
+        this(originUrl, null);
+    }
+
+    void configUrlConnection() throws IOException {
+        Util.d(TAG, "config connection for " + url);
+        if (configuration != null && configuration.proxy != null) {
+            connection = url.openConnection(configuration.proxy);
+        } else {
+            connection = url.openConnection();
+        }
+        if (connection instanceof HttpURLConnection) {
+            ((HttpURLConnection) connection).setInstanceFollowRedirects(false);
+        }
+        if (configuration != null) {
+            if (configuration.readTimeout != null) {
+                connection.setReadTimeout(configuration.readTimeout);
+            }
+
+            if (configuration.connectTimeout != null) {
+                connection.setConnectTimeout(configuration.connectTimeout);
+            }
+        }
+    }
+
+    @Override
+    public void addHeader(String name, String value) {
+        connection.addRequestProperty(name, value);
+    }
+
+    @Override
+    public Connected execute() throws IOException {
+        final Map<String, List<String>> headerProperties = getRequestProperties();
+        connection.connect();
+        redirectHandler.handleRedirect(this, this, headerProperties);
+        return this;
+    }
+
+    @Override
+    public int getResponseCode() throws IOException {
+        if (connection instanceof HttpURLConnection) {
+            return ((HttpURLConnection) connection).getResponseCode();
+        }
+
+        return DownloadConnection.NO_RESPONSE_CODE;
+    }
+
+    @Override
+    public InputStream getInputStream() throws IOException {
+        String ip = NetUtil.getUrlIp(connection);
+        if ("0.0.0.0".equals(ip)) {
+            try {
+                InetSocketAddress address = new InetSocketAddress(url.getHost(), url.getPort());
+                ip = address.getAddress().getHostAddress();
+            } catch (Exception e) {
+                e.printStackTrace();
+            }
+        }
+        ((SheepDownloadConnection.Factory) OkDownload.with().connectionFactory()).setIp(url.toString(), ip);
+        return connection.getInputStream();
+    }
+
+    @Override
+    public boolean setRequestMethod(@NonNull String method) throws ProtocolException {
+        if (connection instanceof HttpURLConnection) {
+            ((HttpURLConnection) connection).setRequestMethod(method);
+            return true;
+        }
+
+        return false;
+    }
+
+    @Override
+    public Map<String, List<String>> getResponseHeaderFields() {
+        return connection.getHeaderFields();
+    }
+
+    @Override
+    public String getResponseHeaderField(String name) {
+        return connection.getHeaderField(name);
+    }
+
+    @Override
+    public String getRedirectLocation() {
+        return redirectHandler.getRedirectLocation();
+    }
+
+    @Override
+    public void release() {
+        // the same to response#close on okhttp
+        // real execute RealBufferedSource.InputStream#close
+        try {
+            final InputStream inputStream = connection.getInputStream();
+            if (inputStream != null) inputStream.close();
+        } catch (IOException ignored) {
+        }
+    }
+
+    @Override
+    public Map<String, List<String>> getRequestProperties() {
+        return connection.getRequestProperties();
+    }
+
+    @Override
+    public String getRequestProperty(String key) {
+        return connection.getRequestProperty(key);
+    }
+
+    public static class Factory implements DownloadConnection.Factory {
+
+        private final Configuration configuration;
+
+        private Map<String, String> ipPool = new HashMap<>();
+
+        public Factory() {
+            this(null);
+        }
+
+        public Factory(Configuration configuration) {
+            this.configuration = configuration;
+        }
+
+        public void setIp(String url, String ip) {
+            ipPool.put(url, ip);
+        }
+
+        public String getIp(String url) {
+            return ipPool.containsKey(url) ? ipPool.get(url) : "0.0.0.0";
+        }
+
+        DownloadConnection create(URL url) throws IOException {
+            return new SheepDownloadConnection(url, configuration);
+        }
+
+        @Override
+        public DownloadConnection create(String originUrl) throws IOException {
+            return new SheepDownloadConnection(originUrl, configuration);
+        }
+    }
+
+    /**
+     * The sample configuration for the {@link SheepDownloadConnection}
+     */
+    @SuppressWarnings("PMD.AvoidFieldNameMatchingMethodName")
+    public static class Configuration {
+        private Proxy proxy;
+        private Integer readTimeout;
+        private Integer connectTimeout;
+
+        /**
+         * The connection will be made through the specified proxy.
+         * <p>
+         * This {@code proxy} will be used when invoke {@link URL#openConnection(Proxy)} }
+         *
+         * @param proxy the proxy will be applied to the {@link SheepDownloadConnection}
+         */
+        public Configuration proxy(Proxy proxy) {
+            this.proxy = proxy;
+            return this;
+        }
+
+        /**
+         * Sets the read timeout to a specified timeout, in milliseconds. A non-zero value specifies
+         * the timeout when reading from Input stream when a connection is established to a
+         * resource.
+         * If the timeout expires before there is data available for read, a
+         * java.net.SocketTimeoutException is raised. A timeout of zero is interpreted as an
+         * infinite timeout.
+         * <p>
+         * This {@code readTimeout} will be applied through
+         * {@link URLConnection#setReadTimeout(int)}
+         *
+         * @param readTimeout an <code>int</code> that specifies the timeout value to be used in
+         *                    milliseconds
+         */
+        public Configuration readTimeout(int readTimeout) {
+            this.readTimeout = readTimeout;
+            return this;
+        }
+
+        /**
+         * Sets a specified timeout value, in milliseconds, to be used when opening a communications
+         * link to the resource referenced by this URLConnection.  If the timeout expires before the
+         * connection can be established, a java.net.SocketTimeoutException is raised. A timeout of
+         * zero is interpreted as an infinite timeout.
+         * <p>
+         * This {@code connectionTimeout} will be applied through
+         * {@link URLConnection#setConnectTimeout(int)}
+         *
+         * @param connectTimeout an <code>int</code> that specifies the connect timeout value in
+         *                       milliseconds
+         */
+        public Configuration connectTimeout(int connectTimeout) {
+            this.connectTimeout = connectTimeout;
+            return this;
+        }
+
+    }
+
+    static final class RedirectHandler implements IRedirectHandler {
+
+        String redirectLocation;
+
+        @Override
+        public void handleRedirect(
+                DownloadConnection originalConnection,
+                Connected originalConnected,
+                Map<String, List<String>> headerProperties) throws IOException {
+            int responseCode = originalConnected.getResponseCode();
+            int redirectCount = 0;
+            final SheepDownloadConnection downloadUrlConnection =
+                    (SheepDownloadConnection) originalConnection;
+            while (RedirectUtil.isRedirect(responseCode)) {
+                // the last connect is useless, so release it
+                downloadUrlConnection.release();
+
+                if (++redirectCount > RedirectUtil.MAX_REDIRECT_TIMES) {
+                    throw new ProtocolException("Too many redirect requests: " + redirectCount);
+                }
+
+                redirectLocation = RedirectUtil
+                        .getRedirectedUrl(originalConnected, responseCode);
+                downloadUrlConnection.url = new URL(redirectLocation);
+                downloadUrlConnection.configUrlConnection();
+                Util.addRequestHeaderFields(headerProperties,
+                        downloadUrlConnection);
+                downloadUrlConnection.connection.connect();
+                responseCode = downloadUrlConnection.getResponseCode();
+            }
+        }
+
+        @Nullable
+        @Override
+        public String getRedirectLocation() {
+            return redirectLocation;
+        }
+    }
+}

+ 4 - 0
app/src/main/java/com/sheep/jiuyan/samllsheep/SheepApp.java

@@ -22,6 +22,7 @@ import com.danikula.videocache.HttpProxyCacheServer;
 //import com.didi.virtualapk.PluginManager;
 //import com.didi.virtualapk.PluginManager;
 import com.kfzs.cfyl.share_library.util.ContextHolder;
 import com.kfzs.cfyl.share_library.util.ContextHolder;
 import com.liulishuo.okdownload.OkDownload;
 import com.liulishuo.okdownload.OkDownload;
+import com.liulishuo.okdownload.core.connection.DownloadUrlConnection;
 import com.liulishuo.okdownload.core.dispatcher.DownloadDispatcher;
 import com.liulishuo.okdownload.core.dispatcher.DownloadDispatcher;
 import com.sheep.gamegroup.di.components.DaggerNetComponent;
 import com.sheep.gamegroup.di.components.DaggerNetComponent;
 import com.sheep.gamegroup.di.components.NetComponent;
 import com.sheep.gamegroup.di.components.NetComponent;
@@ -43,6 +44,7 @@ import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.MyFileNameGenerator;
 import com.sheep.gamegroup.util.MyFileNameGenerator;
 import com.sheep.gamegroup.util.NetUtil;
 import com.sheep.gamegroup.util.NetUtil;
 import com.sheep.gamegroup.util.RefreshUtil;
 import com.sheep.gamegroup.util.RefreshUtil;
+import com.sheep.gamegroup.util.SheepDownloadConnection;
 import com.sheep.gamegroup.util.SysAppUtil;
 import com.sheep.gamegroup.util.SysAppUtil;
 import com.sheep.gamegroup.util.TextToSpeechUtil;
 import com.sheep.gamegroup.util.TextToSpeechUtil;
 import com.sheep.gamegroup.util.UMConfigUtils;
 import com.sheep.gamegroup.util.UMConfigUtils;
@@ -309,6 +311,8 @@ public class SheepApp extends MultiDexApplication {
         initBdLocationOption();
         initBdLocationOption();
 
 
         //设置下载工具
         //设置下载工具
+        OkDownload downloader = new OkDownload.Builder(this).connectionFactory(new SheepDownloadConnection.Factory()).build();
+        OkDownload.setSingletonInstance(downloader);
         DownloadDispatcher.setMaxParallelRunningCount(1000);//在这里,下载框架好像有个bug,如果设置为5,第一个下载会占4个,第二个下载就只有一个在下载,就会失败
         DownloadDispatcher.setMaxParallelRunningCount(1000);//在这里,下载框架好像有个bug,如果设置为5,第一个下载会占4个,第二个下载就只有一个在下载,就会失败
 
 
 //        RemitStoreOnSQLite.setRemitToDBDelayMillis(3000);
 //        RemitStoreOnSQLite.setRemitToDBDelayMillis(3000);

+ 5 - 32
app/src/main/java/com/sheep/jiuyan/samllsheep/service/DownloadService.java

@@ -28,6 +28,7 @@ import com.kfzs.duanduan.utils.ApkUtils;
 import com.kfzs.duanduan.view.DialogStorageLow;
 import com.kfzs.duanduan.view.DialogStorageLow;
 import com.liulishuo.okdownload.DownloadListener;
 import com.liulishuo.okdownload.DownloadListener;
 import com.liulishuo.okdownload.DownloadTask;
 import com.liulishuo.okdownload.DownloadTask;
+import com.liulishuo.okdownload.OkDownload;
 import com.liulishuo.okdownload.SpeedCalculator;
 import com.liulishuo.okdownload.SpeedCalculator;
 import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
 import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
 import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
 import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
@@ -45,6 +46,8 @@ import com.sheep.gamegroup.util.DownloadUtil;
 import com.sheep.gamegroup.util.FileUtil;
 import com.sheep.gamegroup.util.FileUtil;
 import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.LogUtil;
 import com.sheep.gamegroup.util.Md5Util;
 import com.sheep.gamegroup.util.Md5Util;
+import com.sheep.gamegroup.util.NetUtil;
+import com.sheep.gamegroup.util.SheepDownloadConnection;
 import com.sheep.gamegroup.util.StringUtils;
 import com.sheep.gamegroup.util.StringUtils;
 import com.sheep.gamegroup.util.TestUtil;
 import com.sheep.gamegroup.util.TestUtil;
 import com.sheep.gamegroup.view.activity.NotificationsUtils;
 import com.sheep.gamegroup.view.activity.NotificationsUtils;
@@ -56,8 +59,6 @@ import org.greenrobot.eventbus.EventBus;
 
 
 import java.io.File;
 import java.io.File;
 import java.io.InputStream;
 import java.io.InputStream;
-import java.lang.reflect.Field;
-import java.net.InetSocketAddress;
 import java.net.URL;
 import java.net.URL;
 import java.net.URLConnection;
 import java.net.URLConnection;
 import java.util.HashMap;
 import java.util.HashMap;
@@ -66,8 +67,6 @@ import java.util.Locale;
 import java.util.Map;
 import java.util.Map;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicInteger;
 
 
-import okhttp3.Route;
-
 import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;
 import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;
 
 
 /**
 /**
@@ -285,10 +284,11 @@ public class DownloadService extends Service {
                     return;
                     return;
                 }
                 }
                 if (!clientMd5.equals(serverMd5)) {
                 if (!clientMd5.equals(serverMd5)) {
+                    String ip = ((SheepDownloadConnection.Factory) OkDownload.with().connectionFactory()).getIp(new URL(task.getRedirectLocation()).toString());
                     CommonUtil.getInstance().statGameDownloadError(
                     CommonUtil.getInstance().statGameDownloadError(
                             info.getMGameID() + "",
                             info.getMGameID() + "",
                             task.getRedirectLocation(),
                             task.getRedirectLocation(),
-                            getCdbIp(task.getRedirectLocation()),
+                            ip,
                             clientMd5,
                             clientMd5,
                             serverMd5);
                             serverMd5);
                 }
                 }
@@ -300,33 +300,6 @@ public class DownloadService extends Service {
         }).start();
         }).start();
     }
     }
 
 
-    private String getCdbIp(String url) {
-        try {
-            URLConnection conn = new URL(url).openConnection();
-            InputStream in = conn.getInputStream();
-            try {
-                Field delegateField = conn.getClass().getDeclaredField("delegate");
-                delegateField.setAccessible(true);
-                Object delegate = delegateField.get(conn);
-                Field routeField = delegate.getClass().getDeclaredField("route");
-                routeField.setAccessible(true);
-                Object route = routeField.get(delegate);
-                Field inetField = route.getClass().getDeclaredField("inetSocketAddress");
-                inetField.setAccessible(true);
-                InetSocketAddress address = (InetSocketAddress) inetField.get(route);
-                String ip = address.getAddress().getHostAddress();
-                in.close();
-                return ip;
-            } catch (Exception e) {
-                e.printStackTrace();
-                return "";
-            }
-        } catch (Exception e) {
-            e.printStackTrace();
-            return "";
-        }
-    }
-
     @Nullable
     @Nullable
     @Override
     @Override
     public IBinder onBind(Intent intent) {
     public IBinder onBind(Intent intent) {