Ejemplo n.º 1
0
  public SetIfModifiedSince() throws Exception {

    serverSock = new ServerSocket(0);
    int port = serverSock.getLocalPort();

    Thread thr = new Thread(this);
    thr.start();

    Date date = new Date(new Date().getTime() - 1440000); // this time yesterday
    URL url;
    HttpURLConnection con;

    // url = new URL(args[0]);
    url = new URL("http://localhost:" + String.valueOf(port) + "/anything");
    con = (HttpURLConnection) url.openConnection();

    con.setIfModifiedSince(date.getTime());
    con.connect();
    int ret = con.getResponseCode();

    if (ret == 304) {
      System.out.println("Success!");
    } else {
      throw new RuntimeException(
          "Test failed! Http return code using setIfModified method is:"
              + ret
              + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method");
    }
  }
Ejemplo n.º 2
0
  public static HttpURLConnection download(final HttpURLConnection con, final File file)
      throws IOException {
    if (file.exists()) {
      con.setIfModifiedSince(file.lastModified());
      con.connect();
      if (con.getResponseCode() == HttpURLConnection.HTTP_NOT_MODIFIED) {
        log.fine("Using " + file.getName() + " from cache");
        con.disconnect();
        return con;
      }
    }

    log.fine("Downloading new " + file.getName());

    final byte[] buffer = downloadBinary(con);

    if (!file.exists()) {
      file.createNewFile();
    }
    if (file.exists() && (!file.canRead() || file.canWrite())) {
      file.setReadable(true);
      file.setWritable(true);
    }
    if (file.exists() && file.canRead() && file.canWrite()) {
      final FileOutputStream fos = new FileOutputStream(file);
      fos.write(buffer);
      fos.flush();
      fos.close();
    }

    file.setLastModified(con.getLastModified());

    con.disconnect();
    return con;
  }
 @Override
 public void setIfModifiedSince(long newValue) {
   super.setIfModifiedSince(newValue);
   if (ifModifiedSince != 0) {
     requestHeaders.set("If-Modified-Since", HttpDate.format(new Date(ifModifiedSince)));
   } else {
     requestHeaders.removeAll("If-Modified-Since");
   }
 }
Ejemplo n.º 4
0
 /**
  * A slightly different implementation from this parent's <code>setIfModifiedSince()</code> Since
  * this HTTP impl supports IfModifiedSince as one of the header field, the request header is
  * updated with the new value.
  *
  * @param newValue the number of millisecond since epoch
  * @throws IllegalStateException if already connected.
  */
 @Override
 public void setIfModifiedSince(long newValue) {
   super.setIfModifiedSince(newValue);
   // convert from millisecond since epoch to date string
   SimpleDateFormat sdf =
       new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US); // $NON-NLS-1$
   sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // $NON-NLS-1$
   String date = sdf.format(new Date(newValue));
   reqHeader.add("If-Modified-Since", date); // $NON-NLS-1$
 }
Ejemplo n.º 5
0
 @Override
 public void setIfModifiedSince(long newValue) {
   super.setIfModifiedSince(newValue);
   if (ifModifiedSince != 0) {
     SimpleDateFormat format = new SimpleDateFormat(HTTP_DATE_FORMAT);
     String dateString = format.format(new Date(ifModifiedSince));
     setHeader("If-Modified-Since", dateString);
   } else {
     removeHeader("If-Modified-Since");
   }
 }
Ejemplo n.º 6
0
  @Override
  public boolean send() {
    boolean isSuccess = false;

    HttpURLConnection conn = null;

    ByteArrayOutputStream output = null;

    InputStream input = null;
    String strNetTypeName = "";

    try {
      String sUrl = getUrl();
      if (sUrl == null) {
        throw new Exception("you have not set request url");
      }

      sUrl =
          sUrl
              + (getData() == null
                  ? ""
                  : ((sUrl.indexOf("?") > -1 ? (sUrl.endsWith("&") ? "" : "&") : "?")
                      + getParamString()));

      Log.d(LOG_TAG, getId() + ":" + sUrl);

      URL url = new URL(sUrl);

      conn = getConnect(mContext, url);
      checkCacnelStatus();
      conn.setConnectTimeout(getConnectTimeout());
      conn.setReadTimeout(getGetDataTimeout());

      final HashMap<String, String> header = getRequestHeader();
      if (null != header) {
        final Iterator<Entry<String, String>> inerator = header.entrySet().iterator();
        while (inerator.hasNext()) {
          Entry<String, String> entry = inerator.next();
          conn.setRequestProperty(entry.getKey(), entry.getValue());
          //	Log.d("||" + entry.getKey(), entry.getValue());
        }
      }

      if (mIfModifiedSince > 0) {
        conn.setIfModifiedSince(mIfModifiedSince);
      }

      requestStart = new Date().getTime();
      checkCacnelStatus();
      conn.connect();
      checkCacnelStatus();
      final int responseCode = conn.getResponseCode();

      mHttpStatus = responseCode;

      if (responseCode == HttpStatus.SC_NOT_MODIFIED) {
        setResponseHeader(conn);
        requestEnd = new Date().getTime();
        return true;
      }

      if (responseCode != HttpStatus.SC_OK) {
        Log.d(LOG_TAG, responseCode + "|||");
        throw new java.net.SocketException("http status is not 200 or 304");
      }

      if (conn.getContentType().contains("text/vnd.wap.wml") == true && tryCount < getTryLimit()) {
        tryCount++;
        return send();
      }

      output = new ByteArrayOutputStream();

      input = conn.getInputStream();

      final int totalSize = conn.getContentLength();

      int num = 0, downLoaded = 0;

      byte[] buf = new byte[BUFFERSIZE];
      while (mIsNeedResponse && !checkCacnelStatus() && (num = input.read(buf)) != -1) {
        output.write(buf, 0, num);
        downLoaded += num;
        if (mOnProgressListener != null) {
          long now = ToolUtil.getCurrentTime();
          if (now - lastProgressNotifyTime > PROGRESS_NOTIFY_OFFSET) {
            lastProgressNotifyTime = now;
            mOnProgressListener.onProgress(null, downLoaded, totalSize);
          }
        }
      }
      checkCacnelStatus();

      requestEnd = ToolUtil.getCurrentTime();
      checkCacnelStatus();
      setResult(conn, output);
      buf = null;
      isSuccess = true;
    } catch (CancelException ex) {
      Log.e(LOG_TAG, "HttpStatus = " + mHttpStatus + "\n" + ToolUtil.getStackTraceString(ex));
    } catch (java.net.ConnectException ex) {
      Log.e(
          LOG_TAG,
          "HttpStatus = " + mHttpStatus + "\n" + ToolUtil.getStackTraceString(ex) + " " + getId());
      strNetTypeName = HttpUtil.getNetTypeName();
      StatisticsEngine.trackEvent(
          IcsonApplication.app,
          "http_connect_exception",
          "network: " + strNetTypeName + ", HttpStatus = " + mHttpStatus);
    } catch (java.net.SocketException ex) {
      Log.e(
          LOG_TAG,
          "HttpStatus = " + mHttpStatus + "\n" + ToolUtil.getStackTraceString(ex) + " " + getId());
      strNetTypeName = HttpUtil.getNetTypeName();
      StatisticsEngine.trackEvent(
          IcsonApplication.app,
          "http_socket_exception",
          "network: " + strNetTypeName + ", HttpStatus = " + mHttpStatus);
    } catch (Exception ex) {
      Log.e(LOG_TAG, ToolUtil.getStackTraceString(ex));
      strNetTypeName = HttpUtil.getNetTypeName();
      StatisticsEngine.trackEvent(
          IcsonApplication.app,
          "http_other_exception",
          "network: " + strNetTypeName + ", HttpStatus = " + mHttpStatus);
    } finally {
      try {
        if (input != null) {
          input.close();
          input = null;
        }
        if (output != null) {
          output.close();
          output = null;
        }
        if (conn != null) {
          conn.disconnect();
          conn = null;
        }
      } catch (Exception ex) {
        Log.e(LOG_TAG, ToolUtil.getStackTraceString(ex));
      }
    }

    return isSuccess;
  }
Ejemplo n.º 7
0
  public static byte[] updateStoredTile(TileStoreEntry tile, HttpMapSource mapSource)
      throws UnrecoverableDownloadException, IOException, InterruptedException {
    final int x = tile.getX();
    final int y = tile.getY();
    final int zoom = tile.getZoom();
    final HttpMapSource.TileUpdate tileUpdate = mapSource.getTileUpdate();

    switch (tileUpdate) {
      case ETag:
        {
          boolean unchanged = hasTileETag(tile, mapSource);
          if (unchanged) {
            if (log.isTraceEnabled())
              log.trace("Data unchanged on server (eTag): " + mapSource + " " + tile);
            return null;
          }
          break;
        }
      case LastModified:
        {
          boolean isNewer = isTileNewer(tile, mapSource);
          if (!isNewer) {
            if (log.isTraceEnabled())
              log.trace("Data unchanged on server (LastModified): " + mapSource + " " + tile);
            return null;
          }
          break;
        }
    }
    HttpURLConnection conn = mapSource.getTileUrlConnection(zoom, x, y);
    if (conn == null)
      throw new UnrecoverableDownloadException(
          "Tile x="
              + x
              + " y="
              + y
              + " zoom="
              + zoom
              + " is not a valid tile in map source "
              + mapSource);

    if (log.isTraceEnabled()) log.trace(String.format("Checking %s %s", mapSource.getName(), tile));

    prepareConnection(conn);

    boolean conditionalRequest = false;

    switch (tileUpdate) {
      case IfNoneMatch:
        {
          if (tile.geteTag() != null) {
            conn.setRequestProperty("If-None-Match", tile.geteTag());
            conditionalRequest = true;
          }
          break;
        }
      case IfModifiedSince:
        {
          if (tile.getTimeLastModified() > 0) {
            conn.setIfModifiedSince(tile.getTimeLastModified());
            conditionalRequest = true;
          }
          break;
        }
    }

    conn.connect();

    Settings s = Settings.getInstance();

    int code = conn.getResponseCode();

    if (conditionalRequest && code == HttpURLConnection.HTTP_NOT_MODIFIED) {
      // Data unchanged on server
      if (s.tileStoreEnabled) {
        tile.update(conn.getExpiration());
        TileStore.getInstance().putTile(tile, mapSource);
      }
      if (log.isTraceEnabled()) log.trace("Data unchanged on server: " + mapSource + " " + tile);
      return null;
    }
    byte[] data = loadBodyDataInBuffer(conn);

    if (code != HttpURLConnection.HTTP_OK) throw new DownloadFailedException(conn, code);

    checkContentType(conn, data);
    checkContentLength(conn, data);

    String eTag = conn.getHeaderField("ETag");
    long timeLastModified = conn.getLastModified();
    long timeExpires = conn.getExpiration();

    Utilities.checkForInterruption();
    TileImageType imageType = Utilities.getImageType(data);
    if (imageType == null)
      throw new UnrecoverableDownloadException("The returned image is of unknown format");
    if (s.tileStoreEnabled) {
      TileStore.getInstance()
          .putTileData(data, x, y, zoom, mapSource, timeLastModified, timeExpires, eTag);
    }
    Utilities.checkForInterruption();
    return data;
  }
 public void setIfModifiedSince(long l) {
   _flddelegate.setIfModifiedSince(l);
 }