import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;
public class HttpFileDownload {
private HttpClient client = null;
private PropertyChangeSupport pcs = null;
public static final String PROGRESS_VALUE_CHANGED = "progress_value_changed";
public static final String PROGRESS_INIT = "progress_init";
private boolean stop = false;
public HttpFileDownload() throws URIException, NullPointerException {
this(null, 0, null, null);
}
public HttpFileDownload(String proxyHost, int proxyPort, String proxyUser,
String proxyPwd) throws URIException, NullPointerException {
pcs = new PropertyChangeSupport(this);
client = new HttpClient();
if (proxyHost != null) {
client.getHostConfiguration().setProxy(proxyHost, proxyPort);
AuthScope auth = new AuthScope(proxyHost, proxyPort);
client.getState().setProxyCredentials(auth,
new UsernamePasswordCredentials(proxyUser, proxyPwd));
}
}
public void download(String url, File dir) throws HttpException,
IOException {
if(!dir.exists())
dir.mkdirs();
GetMethod method = new GetMethod(url);
int index = url.lastIndexOf("/");
String name = url.substring(index+1);
name = name.replaceAll("[^\\d\\.a-zA-Z]", "_");
File f = new File(dir, name);
FileOutputStream fos = new FileOutputStream(f);
client.executeMethod(method);
long size = method.getResponseContentLength();
long value = 0;
pcs.firePropertyChange(PROGRESS_INIT, null, new Long(size));
InputStream is = method.getResponseBodyAsStream();
Header[] hArr = method.getResponseHeaders();
for(Header h : hArr){
System.out.println(h.getName() + " " + h.getValue());
}
byte[] b = new byte[1024 * 100];
int l = is.read(b);
while (l != -1 && !stop) {
value += l;
pcs.firePropertyChange(PROGRESS_VALUE_CHANGED, null, new Long(value));
fos.write(b, 0, l);
l = is.read(b);
}
fos.flush();
fos.close();
if(stop){
f.delete();
method.abort();
}
stop = false;
pcs.firePropertyChange(PROGRESS_VALUE_CHANGED, null, new Long(0));
method.releaseConnection();
}
public void stop(){
stop = true;
}
public void addPropertyChangeListener(PropertyChangeListener l) {
this.pcs.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
this.pcs.removePropertyChangeListener(l);
}
public static void main(String[] args) throws Exception {
HttpFileDownload download = new HttpFileDownload();
File cwd = new File(".");
download.download("http://mirror.deri.at/apache/httpcomponents/commons-httpclient/source/commons-httpclient-3.1-src.zip", cwd);
}
}