Beispiel #1
0
  public boolean doGetSaveFile(
      String urlStr, String path, FileDownloaderHttpHelper.DownloadListener downloadListener) {

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

    boolean result = false;

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

      URL url = new URL(urlStr);
      AppLoggerUtils.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 BufferedOutputStream(new FileOutputStream(file));

      InputStream is = urlConnection.getInputStream();
      String content_encode = urlConnection.getContentEncoding();
      if (!TextUtils.isEmpty(content_encode) && content_encode.equals("gzip")) {
        is = new GZIPInputStream(is);
      }
      in = new BufferedInputStream(is);

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

        bytesum += byteread;
        out.write(buffer, 0, byteread);
        if (downloadListener != null && bytetotal > 0) {
          downloadListener.pushProgress(bytesum, bytetotal);
        }
      }
      if (downloadListener != null) {
        downloadListener.completed();
      }
      AppLoggerUtils.v("download request= " + urlStr + " download finished");
      result = true;

    } catch (IOException e) {
      e.printStackTrace();
      AppLoggerUtils.v("download request= " + urlStr + " download failed");
    } finally {
      Utility.closeSilently(in);
      Utility.closeSilently(out);
      if (urlConnection != null) {
        urlConnection.disconnect();
      }
    }

    return result && ImageUtility.isThisBitmapCanRead(path);
  }