使用http协议获取网络图片

http用于传输WWW方式的数据。http协议采用了请求响应的模型。在android中提供了HttpURLConnection和HttpClient接口开发HTTP程序。下面分别使用这两种方式获取网络图片。

          1.HttpURLConnection

          代码如下:

   

  1. public class HttpURLConnectionActivity extends Activity {  
  2.   
  3.     private ImageView imageView;  
  4.     @Override  
  5.     protected void onCreate(Bundle savedInstanceState) {  
  6.         // TODO Auto-generated method stub  
  7.         super.onCreate(savedInstanceState);  
  8.         setContentView(R.layout.simple1);  
  9.           
  10.         imageView=(ImageView) this.findViewById(R.id.imageView1);  
  11.         //传入网络图片地址  
  12.         try {  
  13.             URL url = new URL("http://news.xinhuanet.com/photo/2012-02/09/122675973_51n.jpg");  
  14.             HttpURLConnection conn= (HttpURLConnection) url.openConnection();  
  15.             conn.setRequestMethod("GET");  
  16.             conn.setConnectTimeout(5*1000);  
  17.             conn.connect();  
  18.             InputStream in=conn.getInputStream();  
  19.             ByteArrayOutputStream bos=new ByteArrayOutputStream();  
  20.             byte[] buffer=new byte[1024];  
  21.             int len = 0;  
  22.             while((len=in.read(buffer))!=-1){  
  23.                 bos.write(buffer,0,len);  
  24.             }  
  25.             byte[] dataImage=bos.toByteArray();  
  26.             bos.close();  
  27.             in.close();  
  28.             Bitmap bitmap=BitmapFactory.decodeByteArray(dataImage, 0, dataImage.length);  
  29.             //Drawable drawable=BitmapDrawable.  
  30.             imageView.setImageBitmap(bitmap);  
  31.         } catch (Exception e) {  
  32.             // TODO Auto-generated catch block  
  33.             e.printStackTrace();  
  34.             Toast.makeText(getApplicationContext(), "图片加载失败", 1).show();  
  35.         }  
  36.           
  37.     }  
  38. }  
public class HttpURLConnectionActivity extends Activity {

	private ImageView imageView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.simple1);
		
		imageView=(ImageView) this.findViewById(R.id.imageView1);
		//传入网络图片地址
		try {
			URL url = new URL("http://news.xinhuanet.com/photo/2012-02/09/122675973_51n.jpg");
			HttpURLConnection conn= (HttpURLConnection) url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5*1000);
			conn.connect();
			InputStream in=conn.getInputStream();
			ByteArrayOutputStream bos=new ByteArrayOutputStream();
			byte[] buffer=new byte[1024];
			int len = 0;
			while((len=in.read(buffer))!=-1){
				bos.write(buffer,0,len);
			}
			byte[] dataImage=bos.toByteArray();
			bos.close();
			in.close();
			Bitmap bitmap=BitmapFactory.decodeByteArray(dataImage, 0, dataImage.length);
			//Drawable drawable=BitmapDrawable.
	        imageView.setImageBitmap(bitmap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			Toast.makeText(getApplicationContext(), "图片加载失败", 1).show();
		}
		
	}
}

           最后不要忘记在manifest.xml加入网络访问权限:
  1. <uses-permission android:name="android.permission.INTERNET" />  
<uses-permission android:name="android.permission.INTERNET" />
         由于访问网络图片是比较耗时的操作,所以在正式项目中使用异步加载图片,效果会更好。

         运行效果:

       

         2.HttpClient

          下面使用HttpClient获取网页内容:

        

  1. public class HttpClientActivity extends Activity {  
  2.   
  3.     private ImageView imageview;  
  4.     private TextView text;  
  5.     @Override  
  6.     protected void onCreate(Bundle savedInstanceState) {  
  7.         // TODO Auto-generated method stub  
  8.         super.onCreate(savedInstanceState);  
  9.         setContentView(R.layout.simple2);  
  10.           
  11.         imageview=(ImageView) this.findViewById(R.id.imageView2);  
  12.         text=(TextView) this.findViewById(R.id.textView2);  
  13.         HttpGet httpGet=new HttpGet("http://cloud.csdn.net/a/20120209/311628.html");  
  14.         HttpClient httpClient=new DefaultHttpClient();  
  15.         try {  
  16.             //得到HttpResponse对象  
  17.             HttpResponse httpResponse=httpClient.execute(httpGet);  
  18.             //HttpResponse的返回结果是不是成功  
  19.             if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){  
  20.                 //得到返回数据的字符串  
  21.                 String dataImageStr=EntityUtils.toString(httpResponse.getEntity());  
  22.                 text.setText(dataImageStr);  
  23.             }  
  24.         } catch (ClientProtocolException e) {  
  25.             // TODO Auto-generated catch block  
  26.             e.printStackTrace();  
  27.         } catch (IOException e) {  
  28.             // TODO Auto-generated catch block  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  
  32. }  
public class HttpClientActivity extends Activity {

	private ImageView imageview;
	private TextView text;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.simple2);
		
		imageview=(ImageView) this.findViewById(R.id.imageView2);
		text=(TextView) this.findViewById(R.id.textView2);
		HttpGet httpGet=new HttpGet("http://cloud.csdn.net/a/20120209/311628.html");
		HttpClient httpClient=new DefaultHttpClient();
		try {
			//得到HttpResponse对象
			HttpResponse httpResponse=httpClient.execute(httpGet);
			//HttpResponse的返回结果是不是成功
			if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				//得到返回数据的字符串
				String dataImageStr=EntityUtils.toString(httpResponse.getEntity());
				text.setText(dataImageStr);
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

       运行效果:

      

        这样就成功加载了网页内容。

     

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值