/*
请求服务器一个资源,将其下载到手机显示,显保存到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));
请求服务器一个资源,将其下载到手机显示,显保存到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));