Estou usando um código fonte que achei na Internet para copiar arquivos da Internet para o meu computador mas ele sempre falha retornando -1 ao tentar pegar o tamanho do arquivo usando a função getContentLenght() da classe HttpURLConnection. Alguém sabe como posso conseguir o tamanho do arquivo usando algum outro método?
O URL que desejo fazer o download é http://www.bovespa.com.br/suplemento/ExecutaAcaoDownload.asp?arquivo=Titulos_Negociaveis.zip
Se alguém conseguir pegar o tamanho desse arquivo usando algum outro método que não seja com o getContentLenght() já me ajudaria bastante, o resto eu me viro.
Pra quem quiser dar uma checada no código fonte, segue abaixo:
Arquivo Download.java
import java.io.;
import java.net.;
class Download implements Runnable {
// Max size of download buffer.
private static final int MAX_BUFFER_SIZE = 1024;
// These are the status names.
public static final String STATUSES[] = {"Downloading",
"Complete", "Error"};
// These are the status codes.
public static final int DOWNLOADING = 0;
public static final int COMPLETE = 1;
public static final int ERROR = 2;
private URL url; // download URL
private int size; // size of download in bytes
private int downloaded; // number of bytes downloaded
private int status; // current status of download
// Constructor for Download.
public Download(URL url) {
this.url = url;
size = -1;
downloaded = 0;
status = DOWNLOADING;
// Begin the download.
download();
}
// Get this download's URL.
public String getUrl() {
return url.toString();
}
// Get this download's size.
public int getSize() {
return size;
}
// Get this download's progress.
public float getProgress() {
return ((float) downloaded / size) * 100;
}
// Get this download's status.
public int getStatus() {
return status;
}
// Mark this download as having an error.
private void error() {
status = ERROR;
stateChanged();
}
// Start or resume downloading.
private void download() {
Thread thread = new Thread(this);
thread.start();
}
// Get file name portion of URL.
private String getFileName(URL url) {
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
// Download file.
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
// Open connection to URL.
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
// Specify what portion of file to download.
connection.setRequestProperty("Range",
"bytes=" + downloaded + "-");
// Connect to server.
connection.connect();
// Make sure response code is in the 200 range.
if (connection.getResponseCode() / 100 != 2) {
System.out.println("1");
error();
}
// Check for valid content length.
int contentLength = connection.getContentLength();
if (contentLength < 1) {
System.out.println(contentLength);
error();
}
/* Set the size for this download if it
hasn't been already set. */
if (size == -1) {
size = contentLength;
stateChanged();
}
// Open file and seek to the end of it.
file = new RandomAccessFile(getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
/* Size buffer according to how much of the
file is left to download. */
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
// Read from server into buffer.
int read = stream.read(buffer);
if (read == -1)
break;
// Write buffer to file.
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
/* Change status to complete if this point was
reached because downloading has finished. */
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
System.out.println(e.getMessage());
error();
} finally {
// Close file.
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
// Close connection to server.
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}
private void stateChanged() {
System.out.println(STATUSES[status]);
}
}
Arquivo Dotine.java
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
public class Dotine {
private static URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
// Make sure URL specifies a file.
if (verifiedUrl.getFile().length() < 2)
return null;
return verifiedUrl;
}
public static void main(String[] args) throws MalformedURLException, IOException {
//http://www.bovespa.com.br/suplemento/ExecutaAcaoDownload.asp?arquivo=Titulos_Negociaveis.zip
URL verifiedUrl = verifyUrl(args[0]);
if (verifiedUrl != null) {
new Download(verifiedUrl);
} else {
System.out.println("Invalid Download URL");
}
}
}