使用HttpURLConnection下载图片

时间:2022-01-10 01:08:58
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast; public class MainActivity extends Activity { static ImageView iv;
static MainActivity ma; static Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case 1:
// 把位图对象显示至ImageView
iv.setImageBitmap((Bitmap) msg.obj);
break;
case 0:
Toast.makeText(ma, "请求失败", Toast.LENGTH_LONG).show();
break;
default:
break;
}
};
}; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = (ImageView) findViewById(R.id.iv);
} public void click(View v) {
final String path = "http://pic51.nipic.com/file/20141027/11284670_094822707000_2.jpg";
final File file = new File(getCacheDir(), "1.jpg");
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
iv.setImageBitmap(bitmap);
} else { Thread t = new Thread() {
@Override
public void run() {
// 下载图片
// 1、确定网址
try {
// 2、把网址封装成一个url对象
URL url = new URL(path);
// 3、获取客户端和服务器的连接对象,此时还没有建立连接
HttpURLConnection conn = (HttpURLConnection) url
.openConnection();
// 4、对连接对象进行初始化
// 设置请求方法,注意大写(GET或者POST)
conn.setRequestMethod("GET");
// 设置连接超时
conn.setConnectTimeout(5000);
// 设置读取超时
conn.setReadTimeout(5000);
// 5、发送请求,与服务器建立连接
conn.connect();
// 如果响应吗为200,说明请求成功
if (conn.getResponseCode() == 200) {
// 获取服务器响应头里的流,流里的数据是客户端请求的数据
InputStream is = conn.getInputStream(); // 存入内存文件
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int i;
while ((i = is.read(buffer)) != -1) {
fos.write(buffer, 0, i);
}
// 读取出流里的数据,并构成位图对象
Bitmap bitmap = BitmapFactory.decodeFile(file
.getAbsolutePath()); // -->由于主线程阻塞,无法显示图片
// 把位图对象显示至ImageView
// iv.setImageBitmap(bitmap); // -->用消息队列解决问题
Message msg = new Message();
// 消息对象可以携带数据
msg.obj = bitmap;
msg.what = 1;
// 把消息发送至主线程的消息队列
handler.sendMessage(msg);
} else {
Message msg = handler.obtainMessage();
msg.what = 0;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
t.start();
}
}
}

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" > <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="click"
android:text="下载图片" /> <ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="match_parent" /> </LinearLayout>