コード例 #1
0
 public void addDownloadListener(FileDownloaderHttpHelper.DownloadListener listener) {
   if (listener == null) {
     return;
   }
   downloadListenerList.addIfAbsent(listener);
   if (progress > 0 && max > 0) {
     listener.pushProgress(progress, max);
   }
 }
コード例 #2
0
  public boolean doGetSaveFile(
      String urlStr, String path, FileDownloaderHttpHelper.DownloadListener downloadListener) {

    File file = FileManager.createNewFileInSDCard(path);
    if (file == null) {
      return false;
    }

    FileOutputStream out = null;
    InputStream in = null;
    HttpURLConnection urlConnection = null;
    try {

      URL url = new URL(urlStr);
      AppLogger.d("download request=" + urlStr);
      Proxy proxy = getProxy();
      if (proxy != null) urlConnection = (HttpURLConnection) url.openConnection(proxy);
      else urlConnection = (HttpURLConnection) url.openConnection();

      urlConnection.setRequestMethod("GET");
      urlConnection.setDoOutput(false);
      urlConnection.setConnectTimeout(DOWNLOAD_CONNECT_TIMEOUT);
      urlConnection.setReadTimeout(DOWNLOAD_READ_TIMEOUT);
      urlConnection.setRequestProperty("Connection", "Keep-Alive");
      urlConnection.setRequestProperty("Charset", "UTF-8");
      urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");

      urlConnection.connect();

      int status = urlConnection.getResponseCode();

      if (status != HttpURLConnection.HTTP_OK) {
        return false;
      }

      int bytetotal = (int) urlConnection.getContentLength();
      int bytesum = 0;
      int byteread = 0;
      out = new FileOutputStream(file);
      in = urlConnection.getInputStream();

      final Thread thread = Thread.currentThread();
      byte[] buffer = new byte[1444];
      while ((byteread = in.read(buffer)) != -1) {
        if (thread.isInterrupted()) {
          file.delete();
          throw new InterruptedIOException();
        }

        bytesum += byteread;
        out.write(buffer, 0, byteread);
        if (downloadListener != null && bytetotal > 0) {
          downloadListener.pushProgress(bytesum, bytetotal);
        }
      }
      return true;

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      Utility.closeSilently(in);
      Utility.closeSilently(out);
      if (urlConnection != null) urlConnection.disconnect();
    }

    return false;
  }