示例#1
0
  /**
   * Performs the web-service call. If the <code>session</code> parameter is <code>non-null</code>
   * then an authenticated call is made. If it's <code>null</code> then an unauthenticated call is
   * made.<br>
   * The <code>apiKey</code> parameter is always required, even when a valid session is passed to
   * this method.
   *
   * @param method The method to call
   * @param apiKey A Last.fm API key
   * @param params Parameters
   * @param session A Session instance or <code>null</code>
   * @return the result of the operation
   */
  private Result call(String method, String apiKey, Map<String, String> params) {
    params =
        new HashMap<String, String>(params); // create new Map in case params is an immutable Map
    InputStream inputStream = null;

    // try to load from cache
    String cacheEntryName = Cache.createCacheEntryName(method, params);
    if (cache != null) {
      inputStream = getStreamFromCache(cacheEntryName);
    }

    // no entry in cache, load from web
    if (inputStream == null) {
      // fill parameter map with apiKey and session info
      params.put(PARAM_API_KEY, apiKey);
      try {
        HttpURLConnection urlConnection = openPostConnection(method, params);
        inputStream = getInputStreamFromConnection(urlConnection);

        if (inputStream == null) {
          this.lastResult =
              Result.createHttpErrorResult(
                  urlConnection.getResponseCode(), urlConnection.getResponseMessage());
          return lastResult;
        } else {
          if (cache != null) {
            long expires = urlConnection.getHeaderFieldDate("Expires", -1);
            if (expires == -1) {
              expires = cache.findExpirationDate(method, params);
            }
            if (expires != -1) {
              cache.store(
                  cacheEntryName, inputStream, expires); // if data wasn't cached store new result
              inputStream = cache.load(cacheEntryName);
              if (inputStream == null) throw new CallException("Caching/Reloading failed");
            }
          }
        }
      } catch (IOException e) {
        throw new CallException(e);
      }
    }

    try {
      Result result = createResultFromInputStream(inputStream);
      if (!result.isSuccessful()) {
        Log.w(TAG, String.format("API call failed with result: %s%n", result));
        if (cache != null) {
          cache.remove(cacheEntryName);
        }
      }
      this.lastResult = result;
      return result;
    } catch (IOException e) {
      throw new CallException(e);
    } catch (SAXException e) {
      throw new CallException(e);
    }
  }