package com.mail;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class HttpClientDownLoadFileTest {
public static void main(String[] args) {
String url="http://dl_dir2.qq.com/invc/xfspeed/qdesk/versetup/QDeskSetup_25_1277.exe";
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
FileOutputStream out=null;
InputStream inputStream=null;
try {
HttpResponse response =client.execute(httpGet);
HttpEntity entity=response.getEntity();
if(entity!=null){
String[] array = url.split("\\/");
String[] fname = array[array.length-1].split("\\.");
String fileName="",extname="";
if(fname.length == 2){
fileName = fname[0];
extname = fname[1];
System.out.println("fileName:"+fileName);
System.out.println("extname:"+extname);
}
File wdFile = new File("d:\\" + fileName+"."+extname);
//文件已存在
if(wdFile.exists()){
fileName += new Date().getTime();
wdFile = new File("d:\\" + fileName+"."+extname);
}
inputStream=entity.getContent();
out= new FileOutputStream(wdFile);
int l;
byte[] tmp = new byte[2048];
while ((l = inputStream.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
inputStream.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}