HttpClient 4 实现文件下载

如果大家对WEB研发有兴趣
可以加入Q群:46176507 共同进步学习
有时需要通过httpclient进行文件下载,下面是文件下载的实现过程

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
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;

public class SearchDomain {

public static void main(String[] args) throws ClientProtocolException, IOException {
//实例化一个HttpClient
HttpClient httpClient = new DefaultHttpClient();
//设定目标站点 web的默认端口80可以不写的 当然如果是其它端口就要标明
HttpHost httpHost = new HttpHost("www.shanhe114.com",80);
//设置需要下载的文件
HttpGet httpGet = new HttpGet("/test.zip");
//这里也可以直接使用httpGet的绝对地址,当然如果不是具体地址不要忘记/结尾
//HttpGet httpGet = new HttpGet("http://www.0431.la/");
//HttpResponse response = httpClient.execute(httpGet);

HttpResponse response = httpClient.execute(httpHost, httpGet);
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
//请求成功
//取得请求内容
HttpEntity entity = response.getEntity();

//显示内容
if (entity != null) {
//这里可以得到文件的类型 如image/jpg /zip /tiff 等等 但是发现并不是十分有效,有时明明后缀是.rar但是取到的是null,这点特别说明
System.out.println(entity.getContentType());
//可以判断是否是文件数据流
System.out.println(entity.isStreaming());
//设置本地保存的文件
File storeFile = new File("c:/0431la.zip");
FileOutputStream output = new FileOutputStream(storeFile);
//得到网络资源并写入文件
InputStream input = entity.getContent();
byte b[] = new byte[1024];
int j = 0;
while( (j = input.read(b))!=-1){
output.write(b,0,j);
}
output.flush();
output.close();
}
if (entity != null) {
entity.consumeContent();
}
}
}
}


需要说明这里我并没验证文件的类型,实际操作中可以通过url的后缀提取 或者ContentType的类型
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值