本文整理汇总了Java中java.net.URLConnection.getContentLength方法的典型用法代码示例。如果您正苦于以下问题:Java URLConnection.getContentLength方法的具体用法?Java URLConnection.getContentLength怎么用?Java URLConnection.getContentLength使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类java.net.URLConnection
的用法示例。
在下文中一共展示了URLConnection.getContentLength方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getBytes
import java.net.URLConnection; //导入方法依赖的package包/类
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: downloadZip
import java.net.URLConnection; //导入方法依赖的package包/类
private void downloadZip(String link) throws MalformedURLException, IOException
{
URL url = new URL(link);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
long max = conn.getContentLength();
gui.setOutputText("Downloding file...");
BufferedOutputStream fOut = new BufferedOutputStream(new FileOutputStream(new File("update.zip")));
byte[] buffer = new byte[32 * 1024];
int bytesRead = 0;
int in = 0;
while ((bytesRead = is.read(buffer)) != -1) {
in += bytesRead;
fOut.write(buffer, 0, bytesRead);
}
fOut.flush();
fOut.close();
is.close();
gui.setOutputText("Download Complete!");
}
示例3: getBytes
import java.net.URLConnection; //导入方法依赖的package包/类
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();
// Fixed #4507227: Slow performance to load
// class and resources. [stanleyh]
//
// Use buffered input stream [stanleyh]
InputStream in = new BufferedInputStream(uc.getInputStream());
byte[] b;
try {
b = IOUtils.readFully(in, len, true);
} finally {
in.close();
}
return b;
}
示例4: initPumping
import java.net.URLConnection; //导入方法依赖的package包/类
private void initPumping(URLConnection connection) throws IOException {
final Date lastModif = new Date(connection.getLastModified());
final URL realUrl = connection.getURL();
final String accept = connection.getHeaderField("Accept-Ranges");
final boolean acceptBytes = accept != null ? accept.contains("bytes"): false;
final long length = connection.getContentLength();
pumping.init(realUrl, length, lastModif, acceptBytes);
}
示例5: saveSEGY
import java.net.URLConnection; //导入方法依赖的package包/类
private void saveSEGY(OutputStream out) throws IOException {
if(image==null) throw new IOException("no image loaded");
String mcsPath = PathUtil.getPath("PORTALS/MULTI_CHANNEL_PATH",
MapApp.BASE_URL+"/data/portals/mcs/");
URL url = URLFactory.url( mcsPath + line.getCruiseID().trim() + "/segy/" +
line.getCruiseID().trim() +"-"+
line.getID().trim() + ".segy" );
URLConnection urlCon = url.openConnection();
BufferedInputStream in = new BufferedInputStream(urlCon.getInputStream());
int length = urlCon.getContentLength();
// Create a JProgressBar + JDialog
JDialog d = new JDialog((Frame)null, "Saving SEGY");
JPanel p = new JPanel(new BorderLayout());
p.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
d.setLocationRelativeTo(null);
JProgressBar pb = new JProgressBar(0,length);
p.add(new JLabel("Saving " + (length / 1000000) + "mb segy file"), BorderLayout.NORTH);
p.add(pb);
d.getContentPane().add(p);
d.pack();
d.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
d.setVisible(true);
byte[] b = new byte[16384];
int read = in.read(b);
while (read != -1) {
out.write(b, 0, read);
pb.setValue(pb.getValue() + read);
pb.repaint();
read = in.read(b);
}
out.flush();
in.close();
d.dispose();
}
示例6: downloadZip
import java.net.URLConnection; //导入方法依赖的package包/类
/** Downloads a zip from the url, into a temp file under the given temp dir. */
@SuppressForbidden(reason = "We use getInputStream to download plugins")
private Path downloadZip(Terminal terminal, String urlString, Path tmpDir) throws IOException {
terminal.println(VERBOSE, "Retrieving zip from " + urlString);
URL url = new URL(urlString);
Path zip = Files.createTempFile(tmpDir, null, ".zip");
URLConnection urlConnection = url.openConnection();
urlConnection.addRequestProperty("User-Agent", "elasticsearch-plugin-installer");
int contentLength = urlConnection.getContentLength();
try (InputStream in = new TerminalProgressInputStream(urlConnection.getInputStream(), contentLength, terminal)) {
// must overwrite since creating the temp file above actually created the file
Files.copy(in, zip, StandardCopyOption.REPLACE_EXISTING);
}
return zip;
}
示例7: doInBackground
import java.net.URLConnection; //导入方法依赖的package包/类
@Override
protected String doInBackground(String... aurl)
{
int count;
try
{
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard" + folder_mire + folder_update + "/mire.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1)
{
total += count;
publishProgress("" + (int)((total*100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
}
catch (Exception e)
{ }
return null;
}
示例8: download
import java.net.URLConnection; //导入方法依赖的package包/类
public boolean download(PublishingPackage publishingPackage) {
File file = new File(getFilePath());
// The URIs have spaces and we need to encode them or we get a 505 error response
String encodedUri = INDICATORS_URL + getUri().trim().replace(" ", "%20");
try {
if (file.exists() && file.length() > 0) {
log.debug("File {} already exists, not downloading.", getFilePath());
return true;
}
file.getParentFile().mkdirs();
file.createNewFile();
try (FileOutputStream fos = new FileOutputStream(file)) {
URL url = new URL(encodedUri);
log.debug("Downloading attachment from: " + url);
URLConnection connection = url.openConnection();
ReadableByteChannel websiteChannel = Channels.newChannel(connection.getInputStream());
long bytesExpected = connection.getContentLength();
FileChannel fileChannel = fos.getChannel();
long bytesRead = 0;
while (bytesRead < bytesExpected) {
long read = fileChannel.transferFrom(websiteChannel, bytesRead, DOWNLOAD_CHUNK_SIZE);
bytesRead += read;
log.debug("Downloaded {} Mb / {} Mb", getMb(bytesRead), getMb(bytesExpected));
}
}
return true;
} catch (Exception e) {
migrationReport.report(publishingPackage.getUniqueIdentifier(), ATTACHMENT_NOT_AVAILABLE, encodedUri);
file.delete(); // Attempt to delete the file as it may be partially downloaded
return false;
}
}
示例9: downloadFile
import java.net.URLConnection; //导入方法依赖的package包/类
public static boolean downloadFile(String url, String location) {
try {
final URLConnection connection = createURLConnection(url);
final int contentLength = connection.getContentLength();
final File destination = new File(location);
if (destination.exists()) {
final URLConnection savedFileConnection = destination.toURI().toURL().openConnection();
if (savedFileConnection.getContentLength() == contentLength) {
return true;
}
} else {
final File parent = destination.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
}
final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
final FileOutputStream fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
fos.close();
} catch (IOException exception) {
exception.printStackTrace();
return false;
}
System.out.println(url + "->" + location);
return new File(location).exists();
}
示例10: doTestUnknownContentLength
import java.net.URLConnection; //导入方法依赖的package包/类
protected void doTestUnknownContentLength(
URL url) throws IOException
{
URLConnection conn = url.openConnection();
long actualContentLength = conn.getContentLength();
assertEquals("Invalid explicit content length",
-1L, actualContentLength);
}
示例11: getFileSize
import java.net.URLConnection; //导入方法依赖的package包/类
@Override
public long getFileSize(String path, boolean virtual) throws IOException {
long fileSize = -1;
try {
URLConnection urlConnection = getURLConnection(path, virtual);
fileSize = urlConnection.getContentLength();
} catch (IOException e) {
// Ignore this. It will always fail for non-file based includes
}
return fileSize;
}
开发者ID:sunmingshuai,项目名称:apache-tomcat-7.0.73-with-comment,代码行数:12,代码来源:SSIServletExternalResolver.java
示例12: checkUnpackLib
import java.net.URLConnection; //导入方法依赖的package包/类
private static void checkUnpackLib(String filename) {
String path = "/native/" + filename;
URL resource = NativeLibraryLoader.class.getResource(path);
if (resource == null) {
System.err.println("Not available in classpath: " + path);
} else {
File file = new File(filename);
try {
URLConnection urlConnection = resource.openConnection();
int length = urlConnection.getContentLength();
long lastModified = urlConnection.getLastModified();
if (!file.exists() || file.length() != length || file.lastModified() != lastModified) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
try {
IoUtils.copyAllBytes(in, out);
} finally {
IoUtils.safeClose(out);
}
} finally {
IoUtils.safeClose(in);
}
if (lastModified > 0) {
file.setLastModified(lastModified);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
示例13: getFileSize
import java.net.URLConnection; //导入方法依赖的package包/类
@Override
public long getFileSize(String path, boolean virtual) throws IOException {
long fileSize = -1;
try {
URLConnection urlConnection = getURLConnection(path, virtual);
fileSize = urlConnection.getContentLength();
} catch (IOException e) {
// Ignore this. It will always fail for non-file based includes
}
return fileSize;
}
示例14: getInputStreamOfURL
import java.net.URLConnection; //导入方法依赖的package包/类
public InputStream getInputStreamOfURL(URL downloadURL, Proxy proxy) throws IOException{
URLConnection ucn = null;
// loop until no more redirections are
for (;;) {
if (Thread.currentThread().isInterrupted()) {
return null;
}
if(proxy != null) {
ucn = downloadURL.openConnection(proxy);
} else {
ucn = downloadURL.openConnection();
}
HttpURLConnection hucn = doConfigureURLConnection(ucn);
if(Thread.currentThread().isInterrupted())
return null;
ucn.connect();
int rc = hucn.getResponseCode();
boolean isRedirect =
rc == HttpURLConnection.HTTP_MOVED_TEMP ||
rc == HttpURLConnection.HTTP_MOVED_PERM;
if (!isRedirect) {
break;
}
String addr = hucn.getHeaderField(HTTP_REDIRECT_LOCATION);
URL newURL = new URL(addr);
if (!downloadURL.getProtocol().equalsIgnoreCase(newURL.getProtocol())) {
throw new ResourceRedirectException(newURL);
}
downloadURL = newURL;
}
ucn.setReadTimeout(10000);
InputStream is = ucn.getInputStream();
streamLength = ucn.getContentLength();
effectiveURL = ucn.getURL();
return is;
}
示例15: downloadFully
import java.net.URLConnection; //导入方法依赖的package包/类
public static void downloadFully(URL url, File target) throws IOException {
// We don't use the settings here explicitly, since HttpRequests picks up the network settings from studio directly.
ProgressHandle handle = ProgressHandle.createHandle("Downloading " + url);
try {
URLConnection connection = url.openConnection();
if (connection instanceof HttpsURLConnection) {
((HttpsURLConnection) connection).setInstanceFollowRedirects(true);
((HttpsURLConnection) connection).setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; PPC; en-US; rv:1.3.1)");
((HttpsURLConnection) connection).setRequestProperty("Accept-Charset", "UTF-8");
((HttpsURLConnection) connection).setDoOutput(true);
((HttpsURLConnection) connection).setDoInput(true);
}
connection.setConnectTimeout(3000);
connection.connect();
int contentLength = connection.getContentLength();
if (contentLength < 1) {
throw new FileNotFoundException();
}
handle.start(contentLength);
OutputStream dest = new FileOutputStream(target);
InputStream in = connection.getInputStream();
int count;
int done = 0;
byte data[] = new byte[BUFFER_SIZE];
while ((count = in.read(data, 0, BUFFER_SIZE)) != -1) {
done += count;
handle.progress(done);
dest.write(data, 0, count);
}
dest.close();
in.close();
} finally {
handle.finish();
if (target.length() == 0) {
try {
target.delete();
} catch (Exception e) {
}
}
}
}