总所周知在Android6.0以后抛弃了对HttpClient的支持,提倡使用HttpURLConnection来网络请求,今天要用的就是使用HttpURLConnection做的一个异步任务下载图片的例子,不罗嗦,上代码:
我这里有一张网络图片的地址
private String image_Path = "http://e.hiphotos.baidu.com/image/pic/item/2fdda3cc7cd98d10b510fdea233fb80e7aec9021.jpg";
然后开始我们的异步任务之旅
public class MyTask extends AsyncTask<String ,Void,Bitmap>{
@Override
protected void onPostExecute(Bitmap bitmap) {
super.onPostExecute(bitmap);
iv_img.setImageBitmap(bitmap);
}
@Override
protected Bitmap doInBackground(String... params) {
URL url=null;
InputStream is=null;
Bitmap bitmap=null;
try{
//设置图片的路径
url=new URL(params[0]);
//开启连接
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
//设置超时的时间
conn.setConnectTimeout(5000);
//设置请求方式为GET
conn.setRequestMethod("GET");
//响应码为200则返回成功
if(conn.getResponseCode()==200){
//获取连接的输入流即图片的输入流
is=conn.getInputStream();
//将流转换为Bitmap
bitmap=BitmapFactory.decodeStream(is);
is.close();
}
}
catch (Exception e){
e.printStackTrace();
}finally {
try {
//关闭流
if (is != null) {
is.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return bitmap;
}
}
注释已经很详细不细说
下面就开始使用了
由于简单我就直接在Activity的Oncreate方法中调用
new MyTask().execute(image_Path);
导致一个简单的异步任务下载图片的例子就完成了,下面我要做的事使用HttpURLconnection下载图片并缓存到本地
public
class
MainActivity
extends
Activity {
private
Context mContext;
private
ImageView image;
// 加载成功
private
static
final
int
LOAD_SUCCESS =
1
;
// 加载失败
private
static
final
int
LOAD_ERROR = -
1
;
// 用于异步的显示图片
private
Handler handler =
new
Handler() {
public
void
handleMessage(Message msg) {
switch
(msg.what) {
//下载成功
case
LOAD_SUCCESS:
// 获取图片的文件对象
File file =
new
File(Environment.getExternalStorageDirectory(),
"pic.jpg"
);
FileInputStream fis =
null
;
try
{
fis =
new
FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
image.setImageBitmap(bitmap);
}
catch
(FileNotFoundException e) {
e.printStackTrace();
}
break
;
//下载失败
case
LOAD_ERROR:
Toast.makeText(mContext,
"加载失败"
,
0
).show();
break
;
}
};
};
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
mContext =
this
;
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
}
// Button的点击事件
public
void
show(View view) {
// 开启新的线程用于下载图片
new
Thread(
new
Runnable() {
public
void
run() {
getPicture();
}
}).start();
}
//下载图片的主方法
private
void
getPicture() {
URL url =
null
;
InputStream is =
null
;
FileOutputStream fos =
null
;
try
{
//构建图片的url地址
url =
new
URL(
"http://avatar.csdn.net/C/6/8/1_bz419927089.jpg"
);
//开启连接
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时的时间,5000毫秒即5秒
conn.setConnectTimeout(
5000
);
//设置获取图片的方式为GET
conn.setRequestMethod(
"GET"
);
//响应码为200,则访问成功
if
(conn.getResponseCode() ==
200
) {
//获取连接的输入流,这个输入流就是图片的输入流
is = conn.getInputStream();
//构建一个file对象用于存储图片
File file =
new
File(Environment.getExternalStorageDirectory(),
"pic.jpg"
);
fos =
new
FileOutputStream(file);
int
len =
0
;
byte
[] buffer =
new
byte
[
1024
];
//将输入流写入到我们定义好的文件中
while
((len = is.read(buffer)) != -
1
) {
fos.write(buffer,
0
, len);
}
//将缓冲刷入文件
fos.flush();
//告诉handler,图片已经下载成功
handler.sendEmptyMessage(LOAD_SUCCESS);
}
}
catch
(Exception e) {
//告诉handler,图片已经下载失败
handler.sendEmptyMessage(LOAD_ERROR);
e.printStackTrace();
}
finally
{
//在最后,将各种流关闭
try
{
if
(is !=
null
) {
is.close();
}
if
(fos !=
null
) {
fos.close();
}
}
catch
(Exception e) {
handler.sendEmptyMessage(LOAD_ERROR);
e.printStackTrace();
}
}
}
}
|