Android利用HTTP协议加载网络图片

转载请注明出处:http://blog.csdn.net/u010214991/article/details/48493647

给出一张图片的网址,我们怎么把这张图片加载到我们的ImageView控件显示呢?

由于采用网络请求,我们必须在AndroidManifest.xml添加权限

由于是网络请求数据,我们必须在开辟一条线程来完成数据请求,得到数据后最终回到主线程刷新UI显示图片即可。

好了,该说的已经说了,下面直接贴代码了。


1、MainActivity.java

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class MainActivity extends Activity {

	private ImageView imageView;
	private final String PATH = "https://www.baidu.com/img/bdlogo.png";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		imageView = (ImageView) findViewById(R.id.imageView1);

		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				HttpClient httpClient = new DefaultHttpClient();
				HttpGet httpGet = new HttpGet(PATH);
				try {
					HttpResponse httpResponse = httpClient.execute(httpGet);
					if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
						byte[] data = EntityUtils.toByteArray(httpResponse
								.getEntity());
						Message message = Message.obtain();
						message.obj = data;
						message.what = RESULT_OK;
						handler.sendMessage(message);
					}
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					if (httpClient != null
							&& httpClient.getConnectionManager() != null) {
						httpClient.getConnectionManager().shutdown();
					}
				}

			}
		}).start();

	}

	public Handler handler = new Handler() {

		public void handleMessage(Message msg) {
			if (msg.what == RESULT_OK) {
				byte[] data = (byte[]) msg.obj;
				Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
						data.length);
				imageView.setImageBitmap(bitmap);
			}

		};
	};

}


2、activity_main.xml



    


3、AndroidManifest.xml



    
    

    
        
            
                

                
            
        
    




你可能感兴趣的:(Android开发,imageview,网络,图片,控件)