Beispiel #1
0
  // Taken from
  // http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
  public Bitmap downloadBitmap(String url) {
    final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {
      HttpResponse response = client.execute(getRequest);
      final int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode != HttpStatus.SC_OK) {
        Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
        return null;
      }

      final HttpEntity entity = response.getEntity();
      if (entity != null) {
        InputStream inputStream = null;
        try {
          inputStream = entity.getContent();
          return decodeBitmap(inputStream);
        } finally {
          if (inputStream != null) {
            inputStream.close();
          }
          entity.consumeContent();
        }
      }
    } catch (Exception e) {
      // Could provide a more explicit error message for IOException or
      // IllegalStateException
      getRequest.abort();
      Log.w("ImageDownloader", "Error while retrieving bitmap from " + url, e);
    } finally {
      if (client != null) {
        client.close();
      }
    }
    return null;
  }
Beispiel #2
0
  private long downloadFile(TTask.Task task) throws Exception {
    this.mAndroidHttpClient = AndroidHttpClient.newInstance(this.TAG);
    HttpGet httpGet = new HttpGet(this.mUrl);
    HttpResponse response = this.mAndroidHttpClient.execute(httpGet);
    this.mTotalSize = response.getEntity().getContentLength();

    File file = new File(this.mFilePath, this.mFileName);

    if ((file.length() > 0L) && (this.mTotalSize > 0L) && (this.mTotalSize > file.length())) {
      httpGet.addHeader("Range", "bytes=" + file.length() + "-");
      this.mPreviousFileSize = file.length();

      this.mAndroidHttpClient.close();
      this.mAndroidHttpClient = AndroidHttpClient.newInstance("DownloadTask");
      response = this.mAndroidHttpClient.execute(httpGet);
      TLog.v(this.TAG, "File is not complete, .");
      TLog.v(
          this.TAG, "download now,File length:" + file.length() + " totalSize:" + this.mTotalSize);
    } else if ((file.exists()) && (this.mTotalSize == file.length())) {
      TLog.v(this.TAG, "Output file already exists. Skipping download.");
      return 0L;
    }

    long storage = TStorageUtils.getAvailableStorage();
    TLog.i(this.TAG, "storage:" + storage + " totalSize:" + this.mTotalSize);
    if (this.mTotalSize - file.length() > storage) {
      setErrorCode(1);
      task.stopTask();
      this.mAndroidHttpClient.close();
      return 0L;
    }
    try {
      this.mRandomAccessFile = new ProgressReportingRandomAccessFile(file, "rw");
    } catch (FileNotFoundException e) {
      TLog.v(this.TAG, "OutputStream Error");
    }

    InputStream input = null;
    try {
      input = response.getEntity().getContent();
    } catch (IOException ex) {
      setErrorCode(3);
      this.mAndroidHttpClient.close();
      TLog.v(this.TAG, "InputStream Error" + ex.getMessage());
      return 0L;
    }

    int bytesCopied = copy(input, this.mRandomAccessFile, task);

    if ((this.mPreviousFileSize + bytesCopied != this.mTotalSize)
        && (this.mTotalSize != -1L)
        && (!task.isCancel())) {
      throw new IOException("Download incomplete: " + bytesCopied + " != " + this.mTotalSize);
    }

    this.mRandomAccessFile.close();
    this.mAndroidHttpClient.close();
    this.mAndroidHttpClient = null;
    this.mRandomAccessFile = null;
    TLog.v(this.TAG, "Download completed successfully.");
    return bytesCopied;
  }
  // #{key}=#{URI.encode(val.to_s)}"
  // so could have add button in itemlist view which takes us to a form
  // should infer language settings from the list we are in
  // want to support addition of sound/image ...
  public CreateItemResult createItem(
      String cue,
      String cue_language,
      String character_cue_text,
      String part_of_speech,
      String response,
      String response_language,
      String character_response_text,
      String list_id) {
    String http_response = "";
    int status_code = 0;
    AndroidHttpClient client = null;
    try {

      URI uri = new URI("http://api.smart.fm/items");
      Log.d("DEBUG", uri.toString());
      HttpPost post = new HttpPost(uri);
      // Main.consumer.setTokenWithSecret(Main.ACCESS_TOKEN,
      // Main.TOKEN_SECRET);// TODO store in preferences ...
      // Main.consumer.sign(post);
      // set POST body
      String post_body =
          "cue[text]="
              + URLEncoder.encode(cue, "UTF-8")
              + "&cue[part_of_speech]="
              + part_of_speech
              + "&cue[language]="
              + cue_language
              + "&response[text]="
              + URLEncoder.encode(response, "UTF-8")
              + "&response[language]="
              + response_language
              + "&api_key="
              + Main.API_KEY
              + "&list_id="
              + list_id;
      if (character_response_text != null && !character_response_text.equals("")) {
        post_body +=
            "&character_response[text]=" + URLEncoder.encode(character_response_text, "UTF-8");
      }

      if (character_cue_text != null && !character_cue_text.equals("")) {
        post_body += "&cue[character]=" + URLEncoder.encode(character_cue_text, "UTF-8");
      }

      Log.d("DEBUG", post_body);
      // username/password here has to match the API key?
      String auth = Main.username(this) + ":" + Main.password(this);
      byte[] bytes = auth.getBytes();
      post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes)));
      // post.setHeader("Authorization",
      // "Basic dGFuc2FrdTpzYW1qb3NlcGg=");
      // [B@434f6610
      // setting content-type is overwritten ...
      post.setHeader("Content-Type", "application/x-www-form-urlencoded");

      post.setHeader("Host", "api.smart.fm");
      HttpEntity entity = new StringEntity(post_body, "UTF-8");
      post.setEntity(entity);

      Header[] array = post.getAllHeaders();
      for (Header h : array) {
        Log.d("DEBUG", h.toString());
      }
      client = AndroidHttpClient.newInstance("Main");
      HttpResponse response1 = client.execute(post);
      status_code = response1.getStatusLine().getStatusCode();
      Log.d("DEBUG", response1.getStatusLine().toString());
      array = response1.getAllHeaders();
      for (Header h : array) {
        Log.d("DEBUG", h.toString());
      }
      long length = response1.getEntity().getContentLength();
      byte[] response_bytes = new byte[(int) length];
      response1.getEntity().getContent().read(response_bytes);
      Log.d("DEBUG", new String(response_bytes));
      http_response = new String(response_bytes);
      // HttpEntity entity = response1.getEntity();
    } catch (IOException e) {
      /* Reset to Default image on any error. */
      e.printStackTrace();
    } catch (URISyntaxException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {

      if (client != null) {
        client.close();
      }
    }

    return new CreateItemResult(status_code, http_response, list_id);
  }