Java Code Examples for java.net.URLConnection#getContentLength()

The following examples show how to use java.net.URLConnection#getContentLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: YTutils.java    From YTPlayer with GNU General Public License v3.0 6 votes vote down vote up
public static long getFileSize(URL url) {
    URLConnection conn = null;
    try {
        conn = url.openConnection();
        if (conn instanceof HttpURLConnection) {
            ((HttpURLConnection) conn).setRequestMethod("HEAD");
        }
        conn.getInputStream();
        return conn.getContentLength();
    } catch (IOException e) {
        Log.e(TAG, "URL-FILE_SIZE ERROR: "+e.getMessage());
        e.printStackTrace();
        return 0;
    } finally {
        if (conn instanceof HttpURLConnection) {
            ((HttpURLConnection) conn).disconnect();
        }
    }
}
 
Example 2
Source File: B7050028.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example 3
Source File: MethodUtil.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
Example 4
Source File: B7050028.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    URLConnection conn = B7050028.class.getResource("B7050028.class").openConnection();
    int len = conn.getContentLength();
    byte[] data = new byte[len];
    InputStream is = conn.getInputStream();
    is.read(data);
    is.close();
    conn.setDefaultUseCaches(false);
    File jar = File.createTempFile("B7050028", ".jar");
    jar.deleteOnExit();
    OutputStream os = new FileOutputStream(jar);
    ZipOutputStream zos = new ZipOutputStream(os);
    ZipEntry ze = new ZipEntry("B7050028.class");
    ze.setMethod(ZipEntry.STORED);
    ze.setSize(len);
    CRC32 crc = new CRC32();
    crc.update(data);
    ze.setCrc(crc.getValue());
    zos.putNextEntry(ze);
    zos.write(data, 0, len);
    zos.closeEntry();
    zos.finish();
    zos.close();
    os.close();
    System.out.println(new URLClassLoader(new URL[] {new URL("jar:" + jar.toURI() + "!/")}, ClassLoader.getSystemClassLoader().getParent()).loadClass(B7050028.class.getName()));
}
 
Example 5
Source File: FileUtils.java    From weblaf with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns file size, located at the specified url.
 *
 * @param url file location url
 * @return file size
 */
public static int getFileSize ( @NotNull final URL url )
{
    try
    {
        // Creating URLConnection
        final URLConnection uc = ProxyManager.getURLConnection ( url );

        // todo This size is limited to maximum of 2GB, should retrieve long instead
        // Retrieving file size
        return uc.getContentLength ();
    }
    catch ( final Exception e )
    {
        throw new UtilityException ( "Unable to retrieve file size for URL: " + url, e );
    }
}
 
Example 6
Source File: MethodUtil.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
private static byte[] getBytes(URL url) throws IOException {
    URLConnection uc = url.openConnection();
    if (uc instanceof java.net.HttpURLConnection) {
        java.net.HttpURLConnection huc = (java.net.HttpURLConnection) uc;
        int code = huc.getResponseCode();
        if (code >= java.net.HttpURLConnection.HTTP_BAD_REQUEST) {
            throw new IOException("open HTTP connection failed.");
        }
    }
    int len = uc.getContentLength();
    InputStream in = new BufferedInputStream(uc.getInputStream());

    byte[] b;
    try {
        b = IOUtils.readFully(in, len, true);
    } finally {
        in.close();
    }
    return b;
}
 
Example 7
Source File: AbstractFileResolvingResource.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public long contentLength() throws IOException {
	URL url = getURL();
	if (ResourceUtils.isFileURL(url)) {
		// Proceed with file system resolution
		return getFile().length();
	}
	else {
		// Try a URL connection content-length header
		URLConnection con = url.openConnection();
		customizeConnection(con);
		return con.getContentLength();
	}
}
 
Example 8
Source File: UrlParser.java    From play-mpc with MIT License 5 votes vote down vote up
private void parsePlaylistM3u(String url) throws IOException
{
	URL website = new URL(url);
	URLConnection conn = website.openConnection();
	
	int size = conn.getContentLength();
	
	if (size > 256 * 1024)
		throw new IllegalArgumentException("File suspiciously big");

	try (InputStream is = conn.getInputStream())
	{
		InputStreamReader read = new InputStreamReader(is, Charset.defaultCharset());
		BufferedReader reader = new BufferedReader(read);
		
		String line;
		while ((line = reader.readLine()) != null)
		{
			int comIdx = line.indexOf('#');
			if (comIdx >= 0)
				line = line.substring(0, comIdx);
			line = line.trim();
			
			if (!line.isEmpty())
				getAll(line);
		}
	}
}
 
Example 9
Source File: DownloadTask.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
private void download(URL url, File outputFile) throws IOException {
    if (outputFile.exists()) {
        log.info("We found an existing file and rename it as *.backup.");
        FileUtil.renameFile(outputFile, new File(outputFile.getAbsolutePath() + ".backup"));
    }

    URLConnection urlConnection = url.openConnection();
    urlConnection.connect();
    int fileSize = urlConnection.getContentLength();
    copyInputStreamToFileNew(urlConnection.getInputStream(), outputFile, fileSize);
}
 
Example 10
Source File: AbstractFileResolvingResource.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public long contentLength() throws IOException {
	URL url = getURL();
	if (ResourceUtils2.isFileURL(url)) {
		// Proceed with file system resolution
		return getFile().length();
	} else {
		// Try a URL connection content-length header
		URLConnection con = url.openConnection();
		customizeConnection(con);
		return con.getContentLength();
	}
}
 
Example 11
Source File: Downloader.java    From Game with GNU General Public License v3.0 5 votes vote down vote up
public void updateJar() {
	boolean success = true;
	try {
		if (checkVersionNumber()) // Check if version is the same
			return; // and return false if it is.

		URL url = new URL(Constants.UPDATE_JAR_URL);

		// Open connection
		URLConnection connection = url.openConnection();
		connection.setConnectTimeout(3000);
		connection.setReadTimeout(3000);

		int size = connection.getContentLength();
		int offset = 0;
		byte[] data = new byte[size];

		InputStream input = url.openStream();

		int readSize;
		while ((readSize = input.read(data, offset, size - offset)) != -1) {
			offset += readSize;
		}

		if (offset != size) {
		} else {
			File file = new File("./" + Constants.JAR_FILENAME);
			FileOutputStream output = new FileOutputStream(file);
			output.write(data);
			output.close();
		}
	} catch (Exception ignored) {
	}

}
 
Example 12
Source File: UrlWebResource.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public UrlWebResource(final URL url, final String path, final String contentType, final boolean cacheable) {
  this.url = checkNotNull(url);
  this.path = checkNotNull(path);
  this.cacheable = cacheable;

  // open connection to get details about the resource
  try {
    final URLConnection connection = this.url.openConnection();
    try (final InputStream ignore = connection.getInputStream()) {
      if (Strings.isNullOrEmpty(contentType)) {
        this.contentType = connection.getContentType();
      }
      else {
        this.contentType = contentType;
      }

      // support for legacy int and modern long content-length
      long detectedSize = connection.getContentLengthLong();
      if (detectedSize == -1) {
        detectedSize = connection.getContentLength();
      }
      this.size = detectedSize;

      this.lastModified = connection.getLastModified();
    }
  }
  catch (IOException e) {
    throw new IllegalArgumentException("Resource inaccessible: " + url, e);
  }
}
 
Example 13
Source File: TestWarURLConnection.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testContentLength() throws Exception {
    File f = new File("test/webresources/war-url-connection.war");
    String fileUrl = f.toURI().toURL().toString();

    URL indexHtmlUrl = new URL("jar:war:" + fileUrl +
            "*/WEB-INF/lib/test.jar!/META-INF/resources/index.html");

    URLConnection urlConn = indexHtmlUrl.openConnection();
    urlConn.connect();

    int size = urlConn.getContentLength();

    Assert.assertEquals(137, size);
}
 
Example 14
Source File: SplashScreen.java    From jdk-1.7-annotated with Apache License 2.0 4 votes vote down vote up
/**
 * Changes the splash screen image. The new image is loaded from the
 * specified URL; GIF, JPEG and PNG image formats are supported.
 * The method returns after the image has finished loading and the window
 * has been updated.
 * The splash screen window is resized according to the size of
 * the image and is centered on the screen.
 *
 * @param imageURL the non-<code>null</code> URL for the new
 *        splash screen image
 * @throws NullPointerException if {@code imageURL} is <code>null</code>
 * @throws IOException if there was an error while loading the image
 * @throws IllegalStateException if the splash screen has already been
 *         closed
 */
public void setImageURL(URL imageURL) throws NullPointerException, IOException, IllegalStateException {
    checkVisible();
    URLConnection connection = imageURL.openConnection();
    connection.connect();
    int length = connection.getContentLength();
    java.io.InputStream stream = connection.getInputStream();
    byte[] buf = new byte[length];
    int off = 0;
    while(true) {
        // check for available data
        int available = stream.available();
        if (available <= 0) {
            // no data available... well, let's try reading one byte
            // we'll see what happens then
            available = 1;
        }
        // check for enough room in buffer, realloc if needed
        // the buffer always grows in size 2x minimum
        if (off + available > length) {
            length = off*2;
            if (off + available > length) {
                length = available+off;
            }
            byte[] oldBuf = buf;
            buf = new byte[length];
            System.arraycopy(oldBuf, 0, buf, 0, off);
        }
        // now read the data
        int result = stream.read(buf, off, available);
        if (result < 0) {
            break;
        }
        off += result;
    }
    synchronized(SplashScreen.class) {
        checkVisible();
        if (!_setImageData(splashPtr, buf)) {
            throw new IOException("Bad image format or i/o error when loading image");
        }
        this.imageURL = imageURL;
    }
}
 
Example 15
Source File: Launcher.java    From rscplus with GNU General Public License v3.0 4 votes vote down vote up
public boolean updateJar() {
  boolean success = true;

  setStatus("Starting rscplus update...");
  setProgress(0, 1);

  try {
    URL url = new URL("https://github.com/RSCPlus/rscplus/releases/download/Latest/rscplus.jar");

    // Open connection
    URLConnection connection = url.openConnection();
    connection.setConnectTimeout(3000);
    connection.setReadTimeout(3000);

    int size = connection.getContentLength();
    int offset = 0;
    byte[] data = new byte[size];

    InputStream input = url.openStream();

    int readSize;
    while ((readSize = input.read(data, offset, size - offset)) != -1) {
      offset += readSize;
      setStatus("Updating rscplus (" + (offset / 1024) + "KiB / " + (size / 1024) + "KiB)");
      setProgress(offset, size);
    }

    if (offset != size) {
      success = false;
    } else {
      // TODO: Get the jar filename in Settings.initDir
      File file = new File(Settings.Dir.JAR + "/rscplus.jar");
      FileOutputStream output = new FileOutputStream(file);
      output.write(data);
      output.close();

      setStatus("rscplus update complete");
    }
  } catch (Exception e) {
    success = false;
  }

  return success;
}
 
Example 16
Source File: TileDownloader.java    From GpsPrune with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Run method, called in separate thread
 */
public void run()
{
	InputStream in = null;
	try
	{
		// System.out.println("TD Running thread to get: " + _url.toString());
		// Set http user agent on connection
		URLConnection conn = _url.openConnection();
		conn.setRequestProperty("User-Agent", "GpsPrune v" + GpsPrune.VERSION_NUMBER);
		in = conn.getInputStream();
		int len = conn.getContentLength();
		if (len > 0)
		{
			byte[] data = new byte[len];
			int totalRead = 0;
			while (totalRead < len)
			{
				int numRead = in.read(data, totalRead, len-totalRead);
				totalRead += numRead;
			}
			Image tile = Toolkit.getDefaultToolkit().createImage(data);
			in.close();

			// Pass back to manager so it can be stored in its memory cache
			_manager.notifyImageLoaded(tile, _layer, _x, _y, _zoom);

			if (!CONNECTION_ACTIVE)
			{
				// We've just come back online, so forget which tiles gave 404 before
				System.out.println("Deleting blocked urls, currently holds " + BLOCKED_URLS.size());
				synchronized(this.getClass())
				{
					BLOCKED_URLS.clear();
				}
				CONNECTION_ACTIVE = true;
			}
		}
	}
	catch (IOException e)
	{
		System.err.println("IOE: " + e.getClass().getName() + " - " + e.getMessage());
		synchronized(this.getClass())
		{
			BLOCKED_URLS.add(_url.toString());
		}
		try {in.close();} catch (Exception e2) {}
		CONNECTION_ACTIVE = false;	// lost connection?
	}
	LOADING_URLS.remove(_url.toString());
}
 
Example 17
Source File: SplashScreen.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Changes the splash screen image. The new image is loaded from the
 * specified URL; GIF, JPEG and PNG image formats are supported.
 * The method returns after the image has finished loading and the window
 * has been updated.
 * The splash screen window is resized according to the size of
 * the image and is centered on the screen.
 *
 * @param imageURL the non-<code>null</code> URL for the new
 *        splash screen image
 * @throws NullPointerException if {@code imageURL} is <code>null</code>
 * @throws IOException if there was an error while loading the image
 * @throws IllegalStateException if the splash screen has already been
 *         closed
 */
public void setImageURL(URL imageURL) throws NullPointerException, IOException, IllegalStateException {
    checkVisible();
    URLConnection connection = imageURL.openConnection();
    connection.connect();
    int length = connection.getContentLength();
    java.io.InputStream stream = connection.getInputStream();
    byte[] buf = new byte[length];
    int off = 0;
    while(true) {
        // check for available data
        int available = stream.available();
        if (available <= 0) {
            // no data available... well, let's try reading one byte
            // we'll see what happens then
            available = 1;
        }
        // check for enough room in buffer, realloc if needed
        // the buffer always grows in size 2x minimum
        if (off + available > length) {
            length = off*2;
            if (off + available > length) {
                length = available+off;
            }
            byte[] oldBuf = buf;
            buf = new byte[length];
            System.arraycopy(oldBuf, 0, buf, 0, off);
        }
        // now read the data
        int result = stream.read(buf, off, available);
        if (result < 0) {
            break;
        }
        off += result;
    }
    synchronized(SplashScreen.class) {
        checkVisible();
        if (!_setImageData(splashPtr, buf)) {
            throw new IOException("Bad image format or i/o error when loading image");
        }
        this.imageURL = imageURL;
    }
}
 
Example 18
Source File: ContentHandler.java    From RTSP-Java-UrlConnection with Apache License 2.0 4 votes vote down vote up
public final Object getContent(URLConnection urlc) throws IOException {
	int l = urlc.getContentLength();
	com.net.rtsp.Debug.println("### BODY CONTENT LENGTH = "+l);
	
	
	if (l > 0) {
		
		byte[] c = new byte[l];
		
		
		urlc.getInputStream().read(c);
		
		com.net.rtsp.Debug.println("### BODY CONTENT  = \n"+new String(c)+"\n####");
		
		if(urlc.getContentType().toLowerCase().equals(getContentType().toLowerCase()))
		   return getResponseContent(c);
	}
	return null;
}
 
Example 19
Source File: FileOperation.java    From Android-POS with MIT License 4 votes vote down vote up
public boolean comparefileSize(String localfilename,String remoteurl){
	long localfile = 0;
	long remotefile = 0;
	
	long lastmodifylocal = 0;
	long lastmodifyremote = 0;
	try{
		if(localfilename != null && remoteurl != null){
			  File fl = ct.getFileStreamPath( localfilename );
			  if(fl.exists()){
				  localfile = fl.length();
				  lastmodifylocal = fl.lastModified();
			  }else{
				  localfile = 0;
				  return false;
			  }
			  
			  URLConnection connect = null;
			  URL newUrl=new URL(remoteurl);
			  connect=newUrl.openConnection();
			  connect.setRequestProperty ("Content-type","application/x-www-form-urlencoded");
			  
			  connect.connect();
			  
			 
			
			  remotefile = connect.getContentLength();
			  lastmodifyremote = connect.getLastModified();
			  Log.i("local file size",localfile+"");
			  Log.i("remote file size",remotefile + "");
			  
			  Log.i("last modify local ",lastmodifylocal+"");
			  Log.i("last modify remote ",lastmodifyremote + "");
			  
			  if(localfile == remotefile){
				  return true;
			  }else{
				  return false;
			  }
		}else{
			return false;
		}
	}catch(Exception e){
		e.printStackTrace();
		return false;
	}
}
 
Example 20
Source File: AjaxHttpRequest.java    From lizzie with GNU General Public License v3.0 4 votes vote down vote up
protected void sendSync(String content) throws IOException {
  if (sent) {
    return;
  }
  try {
    URLConnection c;
    synchronized (this) {
      c = this.connection;
    }
    if (c == null) {
      return;
    }
    sent = true;
    initConnectionRequestHeader(c);
    int istatus;
    String istatusText;
    InputStream err;
    if (c instanceof HttpURLConnection) {
      HttpURLConnection hc = (HttpURLConnection) c;
      String method = this.requestMethod == null ? DEFAULT_REQUEST_METHOD : this.requestMethod;

      method = method.toUpperCase();
      hc.setRequestMethod(method);
      if ("POST".equals(method) && content != null) {
        hc.setDoOutput(true);
        byte[] contentBytes = content.getBytes(postCharset);
        hc.setFixedLengthStreamingMode(contentBytes.length);
        OutputStream out = hc.getOutputStream();
        try {
          out.write(contentBytes);
        } finally {
          out.flush();
        }
      }
      istatus = hc.getResponseCode();
      istatusText = hc.getResponseMessage();
      err = hc.getErrorStream();
    } else {
      istatus = 0;
      istatusText = "";
      err = null;
    }
    synchronized (this) {
      this.responseHeaders = getConnectionResponseHeaders(c);
      this.responseHeadersMap = c.getHeaderFields();
    }
    this.changeState(AjaxHttpRequest.STATE_LOADED, istatus, istatusText, null);
    InputStream in = err == null ? c.getInputStream() : err;
    int contentLength = c.getContentLength();

    this.changeState(AjaxHttpRequest.STATE_INTERACTIVE, istatus, istatusText, null);
    byte[] bytes = loadStream(in, contentLength == -1 ? 4096 : contentLength);
    this.changeState(AjaxHttpRequest.STATE_COMPLETE, istatus, istatusText, bytes);
  } finally {
    synchronized (this) {
      this.connection = null;
      sent = false;
    }
  }
}