Ejemplo n.º 1
0
  /**
   * Reads the content behind a con and returns them. Note: if con==null, the current request is
   * read. This is usefull for redirects. Note #2: if a connection is loaded, data is not stored in
   * the browser instance.
   *
   * @param con
   * @return
   * @throws IOException
   */
  public Request loadConnection(HTTPConnectionImpl con) throws IOException {

    Request requ;
    if (con == null) {
      requ = this.request;
    } else {
      requ =
          new Request(con) {
            {
              this.requested = true;
            }

            @Override
            public long postRequest() throws IOException {
              return 0;
            }

            @Override
            public void preRequest() throws IOException {}
          };
    }
    try {
      this.checkContentLengthLimit(requ);
      con = requ.getHttpConnection();
      /* we update allowedResponseCodes here */
      con.setAllowedResponseCodes(this.allowedResponseCodes);
      requ.read();
    } catch (final BrowserException e) {
      throw e;
    } catch (final IOException e) {
      throw new BrowserException(e.getMessage(), con, e);
    } finally {
      try {
        con.disconnect();
      } catch (final Throwable e) {
      }
    }
    if (this.isVerbose()) {
      final Logger llogger = this.getLogger();
      if (llogger != null) {
        llogger.finest("\r\n" + requ + "\r\n");
      }
    }
    return requ;
  }
Ejemplo n.º 2
0
  /**
   * Lädt über eine URLConnection eine Datei herunter. Zieldatei ist file.
   *
   * @param file
   * @param con
   * @return Erfolg true/false
   * @throws IOException
   */
  public static void download(final File file, final HTTPConnectionImpl con) throws IOException {
    if (file.isFile()) {
      if (!file.delete()) {
        System.out.println("Konnte Datei nicht löschen " + file);
        throw new IOException("Could not overwrite file: " + file);
      }
    }

    final File parentFile = file.getParentFile();
    if (parentFile != null && !parentFile.exists()) {
      parentFile.mkdirs();
    }
    file.createNewFile();
    FileOutputStream fos = null;
    BufferedOutputStream output = null;
    BufferedInputStream input = null;
    boolean okay = false;
    try {
      output = new BufferedOutputStream(fos = new FileOutputStream(file, false));
      input = new BufferedInputStream(con.getInputStream());
      final byte[] b = new byte[1024];
      int len;
      while ((len = input.read(b)) != -1) {
        output.write(b, 0, len);
      }
      okay = true;
    } finally {
      try {
        output.close();
      } catch (final Throwable e) {
      }
      try {
        input.close();
      } catch (final Throwable e) {
      }
      try {
        fos.close();
      } catch (final Throwable e) {
      }
      if (okay == false) {
        file.delete();
      }
    }
  }