package com.ttpod.httpclient;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.
DefaultHttpClient;
/**
?* @className:DownloadFile.java
?* @classDescription:
?* @author:qiuchen
?* @createTime:2012-6-6
?*/
public class DownloadFile {
/**
* 从url中下载资源
* @author:qiuchen
* @createTime:2012-6-6
* @param url 图片资源地址
* @param saveDir 保存磁盘,
* @return
* @throws IOException?
*/
public static boolean downLoadFile(String url) throws IOException{
//从url中获取
文件名
String fileName = getFileNameByUrl(url);
String savePath = "F:\\"+fileName;
System.out.println(savePath);
// 执行请求的客户端
HttpClient client = new DefaultHttpClient();?
// Http Get 请求
HttpGet get = new HttpGet(url);
// 获得服务器响应的所有信息
HttpResponse response = null;
try {
response = client.execute(get);
int state = response.getStatusLine().getStatusCode();
System.out.println(state);
if(state == HttpStatus.SC_OK){
//状态码=200
// 获得服务器响应的信息(除head部分,源代码中是看不到的)
HttpEntity entity = response.getEntity();
System.out.println("fileLength:"+entity.getContentLength());
System.out.println(entity);
//获取输入流
InputStream input = entity.getContent();
//定义输出文件(文件格式要和资源匹配)
FileOutputStream bout = new FileOutputStream(savePath);
byte[] buffer = new byte[1024 * 100000];
int read = 0;
while ((read = input.read(buffer)) > 0) {
bout.write(buffer,0,read);
System.out.println(read);
}
input.close(); // 关闭输入流
bout.close(); //关闭输出流
System.out.println("download success");
}else{
System.out.println("read error");
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
client.getConnectionManager().shutdown();
}
return true;
}
public static void main(String[] args) {
String?url = "http://www.360desk.net/Wallpaper/2010222840dog.jpg";
try {
downLoadFile(url);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 从url地址中
获取文件名
* @author:qiuchen
* @createTime:2012-6-12
* @param url
* @return?
*/
public static String getFileNameByUrl(String url){
int lastNo = url.lastIndexOf("/"); ?//最后一个"/"的索引
if(url.substring(lastNo).lastIndexOf(".")==-1){
//one webpage
return url;
}else{
if("".equals(url.substring(url.lastIndexOf("/")+1,url.lastIndexOf(".")))){
getFileNameByUrl(url.substring(0,url.lastIndexOf("/")));
}else{
return url.substring(url.lastIndexOf("/")+1);
}
}
return url;
}
}