HttpClient download picture

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;
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值