模拟多线程加载网络图片405
package com.example.thread;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
private Handler mHandler;
private ImageView imageView1, imageView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new Handler();
imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView2 = (ImageView) findViewById(R.id.imageView2);
new Thread(new MyThread("http://img0w.pconline.com.cn/pconline/1309/11/3464151_10.jpg", imageView1)).start();
new Thread(new MyThread("http://img0w.pconline.com.cn/pconline/1309/05/3456400_01.jpg", imageView2)).start();
}
class MyThread implements Runnable {
String url;
ImageView view;
private MyThread(String url, ImageView view) {
super();
Log.e("ee", "MyThread");
this.url = url;
this.view = view;
}
@Override
public void run() {
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
connection = (HttpURLConnection) new URL(url).openConnection();
connection.setConnectTimeout(5000); // 与请求网址的服务器建立连接的超时时间
connection.setReadTimeout(5000);//指的是建立连接后如果指定时间内服务器没有返回数据的后超时。
// 设定传送的内容类型是可序列化的java对象
// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
connection.setRequestProperty("Content-type", "application/x-java-serialized-object");
// 设定请求的方法为"POST",默认是GET
connection.setRequestMethod("GET");
// 设置是否从httpUrlConnection读入,默认情况下是true;
connection.setDoInput(true);
// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
// http正文内,因此需要设为true, 默认情况下是false;
// connection.setDoOutput(true);
// Post 请求不能使用缓存
connection.setUseCaches(false);
// 链接
connection.connect();
Log.e("ee", "getResponseCode==" + connection.getResponseCode());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = connection.getInputStream();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
view.setImageBitmap(bitmap);
}
}, 2000);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注销 connection.setDoOutput(true);这句就好了