昨天在写完java下载的文章后就在今天发现了一个问题。通过这个问题也反应出对HttpURLConnection这个类还不了解。趁此机会再添加一些对这个类的了解吧。首先看看前面那断代码在我的程序中出现了什么问题:
在我的程序中有这么一个模块,通过给定的url下载到文件,保存到本地。而文件是binary形式的。例如:http://abc/li.exe,
用下面代码会出现一个问题,就是当这个url被重定向到一个网页时,下载下来的就是网页的内容:
public static File saveToFiles(String destUrl,String path) throws IOException {
final int BUFFER_SIZE = 4096;
System.out.println("file download url is "+destUrl+" path is"+path+"--------------");
FileOutputStream fos = null;
BufferedInputStream bis = null;
HttpURLConnection httpconn = null;
URL url = null;
byte[] buf = new byte[BUFFER_SIZE];
int size = 0;
if(rc.isUseProxy()){ // 此处为读取配置文件的内容,确定是否使用代理
Properties prop = System.getProperties();
//set http proxy addr
prop.setProperty("http.proxyHost", rc.getHttpProxyHost()); //设置代理的Ip
// set http proxy port
prop.setProperty("http.proxyPort", rc.getHttpProxyPort()+""); //设置代理的端口
}
File storeFile = new File(path,System.currentTimeMillis()+".tmp");
System.out.println("file download url is "+destUrl+"path is "+path+"---------------");
// connection
url = new URL(destUrl);
httpconn = (HttpURLConnection) url.openConnection();
httpconn.setRequestProperty("Host", "analigesto.com");
httpconn.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.0.18) Gecko/2010021501 Ubuntu/9.04 (jaunty) Firefox/3.0.18");
httpconn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
httpconn.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5");
httpconn.setRequestProperty("Accept-Encoding", "gzip,deflate");
httpconn.setRequestProperty("Accept-Charset", "gb2312,utf-8;q=0.7,*;q=0.7");
httpconn.setRequestProperty("Keep-Alive", "300");
httpconn.setRequestProperty("Connection", "Keep-Alive");
//httpconn.setRequestProperty("Referer", url);
httpconn.setRequestProperty("Cookie", "PHPSESSID=1d888d20bba26e676811ebf7f0cd109b");
try{
httpconn.setReadTimeout(40000); // 设置读取文件超时时间
httpconn.connect();
int statuscode = httpconn.getResponseCode(); // 建立链接后先查询url的状态码
if(statuscode == 200){ //链接正常。并得到了返回信息
bis = new BufferedInputStream(httpconn.getInputStream()); // 建立管道,准备读取数据流
fos = new FileOutputStream(storeFile);
System.out.println("it is to receive link[" + destUrl + "]content/n be save file is:[" + storeFile
+ "]");
while ((size = bis.read(buf)) != -1){ // 保存文件到本地磁盘
fos.write(buf, 0, size);
}
System.out.println("file download url is "+destUrl+" path is"+path+" "+new Date());
fos.close();
bis.close();
httpconn.disconnect();
System.out.println("saveToFiles file is "+storeFile.getName()+" size is "+storeFile.length());
}else{
return null;
}
}catch(Exception e){
System.out.println(destUrl+" this url connection timeout ");
System.out.println(e.toString());
return null;
}
return storeFile;
}
为了防止下载文件出现这种问题,我们需要在httpconn.connect();完成连接后判断连接到的文件的属性。在此加上一句话
String type = httpconn.getContentType();
if(statuscode == 200 && type.contains("application/")){
//此处与上面相同。
}
这样下载下来的文件就是应用程序而非网页了。当有一个binary文件url被重定向后就可以避免把网页文件当成自己想要下载的内容去下载了----