
我们经常会在网页上进行资料的搜集,然后把适合自己使用的材料进行下载。在学习了java的有关知识后,我们可以对下载的流程进行一个分析,主要是用到了url的方法。在正式开始使用Java下载前,我们先对http下载的内容进行一个流程上的梳理,然后再带来具体的实例代码。
1、下载流程
在Internet上,我们要下载网站上的某一个资源 ,我们会获得一个UR L(UniformResou rce Locator),它是一个服务器资源定位的描述 ,下载的过程经常如下方法:
(1)客户端发起连接请求一个URL
(2)服务器解析URL,并将指定的资源返回一个输入流给客户
(3)客户端接收输入流,将流中的内容存到文件
2、实例
packagecom.hu.down;
importjava.io.BufferedInputStream;
importjava.io.BufferedOutputStream;
importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.net.HttpURLConnection;
importjava.net.MalformedURLException;
importjava.net.URL;
publicclassDownFile{
publicfinalstaticbooleanDEBUG=true;//调试用
privatestaticintBUFFER_SIZE=1024;//缓冲区大小
publicvoidsaveToFile(StringdestUrl){
BufferedInputStreambis=null;
HttpURLConnectionhttpUrl=null;
URLurl=null;
byte[]buf=newbyte[BUFFER_SIZE];
try{
url=newURL(destUrl);
}catch(MalformedURLExceptione){
//TODOAuto-generatedcatchblock
System.out.println(destUrl+"资源URL语法错误,请检查字符串是否正确!");
return;
}
try{
httpUrl=(HttpURLConnection)url.openConnection();
}catch(IOExceptione){
System.out.println("打开到"+destUrl+"所引用的远程对象的连接失败");
}
try{
httpUrl.connect();
}catch(IOExceptione){
System.out.println("打开到此"+destUrl+"引用的资源的通信链接失败");
return;
}
try{
bis=newBufferedInputStream(httpUrl.getInputStream());
}catch(IOExceptione){
System.out.println("取得连接的Input流失败");
return;
}
Filefile=newFile("D:/upload"+destUrl.substring(destUrl.lastIndexOf("/")));
BufferedOutputStreamfileOut=null;
try{
fileOut=newBufferedOutputStream(newFileOutputStream(file));
}catch(FileNotFoundExceptione){
System.out.println(file+"在本地保存文件失败");
e.printStackTrace();
}
try{
while(true){
intbytesIn=bis.read(buf,0,1024);
if(bytesIn==-1){
break;
}else{
fileOut.write(buf,0,bytesIn);
}
}
fileOut.flush();
fileOut.close();
}catch(Exceptionee){
System.out.println(file+"保存文件过程失败");
}
System.out.println(file.getAbsolutePath()+"下载完毕");
}
publicstaticvoidmain(String[]args)throwsIOException{
DownFiled=newDownFile();
Stringyouclass="11003080";
StringbaseUrl="http://photo/"+youclass;
for(inti=301;i<=340;i++)
{
d.saveToFile(baseUrl+i+".jpg");
}
}
}原文来自:https://www.py.cn © 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END



















































暂无评论内容