`
mmdev
  • 浏览: 12893654 次
  • 性别: Icon_minigender_1
  • 来自: 大连
文章分类
社区版块
存档分类
最新评论

Android下载文件显示到ImageView并保存在手机SD卡

 
阅读更多
/*
请求服务器一个资源,将其下载到手机显示,显保存到SD卡中。
通过http的get请求连接服务器,(下载只能用GET方式请求)。如果连接成功服务器端自动会往流中写东西,客户
端只要拿到InputStream就能从中拿到数据。
*/

1、从EditText输入框中得到输入的服务器资源路径
String path = et_path.getText().toString().trim();

2、创建URL地址
URL url = new URL(path);

3、获得HttpURLConnection 连接
HttpURLConnection conn =(HttpURLConnection)url.openConnection();

4、设定请求头:请求方式GET和浏览器类型
conn.setRequestMethod("GET");
conn.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");

5、获取连接响应码,如果成功,下载文件
InputStream is = conn.getInputStream(); //从连接中获取输入流
FileOutputStream fos = new FileOutputStream(file);
byte []buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!= -1){
fos.write(buffer,0,len);
}
fos.close();
is.close();
6、从文件中拿到数据,显示在ImageView件中
lv.setImageURI(Uri.fromFile(file));


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics