java.net.URLConnection#getContentLength ( )源码实例Demo

下面列出了java.net.URLConnection#getContentLength ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: java-n-IDE-for-Android   文件: MethodUtil.java
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;
}
 
源代码2 项目: YTPlayer   文件: YTutils.java
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();
        }
    }
}
 
源代码3 项目: weblaf   文件: FileUtils.java
/**
 * 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 );
    }
}
 
源代码4 项目: TencentKona-8   文件: B7050028.java
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()));
}
 
源代码5 项目: jdk8u-jdk   文件: MethodUtil.java
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;
}
 
源代码6 项目: openjdk-8-source   文件: B7050028.java
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()));
}
 
@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);
}
 
源代码8 项目: nexus-public   文件: UrlWebResource.java
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);
  }
}
 
源代码9 项目: Game   文件: Downloader.java
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) {
	}

}
 
源代码10 项目: lams   文件: AbstractFileResolvingResource.java
@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();
	}
}
 
@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();
	}
}
 
源代码12 项目: bisq   文件: DownloadTask.java
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);
}
 
源代码13 项目: play-mpc   文件: UrlParser.java
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);
		}
	}
}
 
源代码14 项目: Android-POS   文件: FileOperation.java
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;
	}
}
 
源代码15 项目: RTSP-Java-UrlConnection   文件: ContentHandler.java
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;
}
 
源代码16 项目: hottub   文件: SplashScreen.java
/**
 * 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;
    }
}
 
源代码17 项目: jdk-1.7-annotated   文件: SplashScreen.java
/**
 * 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;
    }
}
 
源代码18 项目: rscplus   文件: Launcher.java
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;
}
 
源代码19 项目: GpsPrune   文件: TileDownloader.java
/**
 * 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());
}
 
源代码20 项目: lizzie   文件: AjaxHttpRequest.java
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;
    }
  }
}