手机站
网通分站
电信主站
密 码:
用户名:
热门关键字:  虚拟主机  cn域名  域名注册  非法  seo
当前位置 : 主页>程序设计>Java技术>列表

Java实现HTTP文件下载

来源:互联网 作者:west263.com 时间:2008-02-23 点击:
西部数码-全国虚拟主机10强!40余项虚拟主机管理功能,全国领先!双线多线虚拟主机南北访问畅通无阻!免费赠送企业邮局,.CN域名,自助建站480元起,免费试用7天,满意再付款! P4主机租用799元/月.月付免压金!

if (this.DEBUG)
System.out.println("正在获取链接[" destUrl "]的内容...\n将其保存为文件["
fileName "]");
//保存文件
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);

fos.close();
bis.close();
httpUrl.disconnect();
}

/**
* 将HTTP资源另存为文件
*
* @param destUrl String
* @param fileName String
* @throws Exception
*/
public void saveToFile2(String destUrl, String fileName) throws IOException {
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpUrl = null;
URL url = null;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;

//建立链接
url = new URL(destUrl);
httpUrl = (HttpURLConnection) url.openConnection();

// String authString = "username" ":" "password";
String authString = "50301" ":" "88888888";
String auth = "Basic "
new sun.misc.BASE64Encoder().encode(authString.getBytes());
httpUrl.setRequestProperty("Proxy-Authorization", auth);

//连接指定的资源
httpUrl.connect();
//获取网络输入流
bis = new BufferedInputStream(httpUrl.getInputStream());
//建立文件
fos = new FileOutputStream(fileName);

if (this.DEBUG)
System.out.println("正在获取链接[" destUrl "]的内容...\n将其保存为文件["
fileName "]");
//保存文件
while ((size = bis.read(buf)) != -1)
fos.write(buf, 0, size);

fos.close();
bis.close();
httpUrl.disconnect();
}

/**
* 设置代理服务器
*
* @param proxy String
* @param proxyPort String
*/
public void setProxyServer(String proxy, String proxyPort) {
//设置代理服务器
System.getProperties().put("proxySet", "true");
System.getProperties().put("proxyHost", proxy);
System.getProperties().put("proxyPort", proxyPort);
}

public void setAuthenticator(String uid, String pwd) {
Authenticator.setDefault(new MyAuthenticator());
}

/**
* 主方法(用于测试)
*
* @param argv String[]
*/
public static void main(String argv[]) {
HttpGet oInstance = new HttpGet();
try {
// //增加下载列表(此处用户可以写入自己代码来增加下载列表)
// oInstance.addItem("http://www.ebook.com/java/网络编程001.zip","./网络编程1.zip");//
// oInstance.addItem("http://www.ebook.com/java/网络编程002.zip","./网络编程2.zip");
// oInstance.addItem("http://www.ebook.com/java/网络编程003.zip","./网络编程3.zip");
// //开始下载
// oInstance.downLoadByList();
oInstance.saveToFile("http://www.ebook.com/java/网络编程001.zip", "./down.zip");
}
catch (Exception err) {
System.out.println(err.getMessage());
}
}
}


上一篇: 多核、超线程CPU时代将成就Java性能之王的地位
下一篇: [转]从Java开源说起

文章整理:西部数码--专业提供域名注册虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

共2页: 上一页 [1] 2 下一页
最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名
注册