当前位置: 代码迷 >> Android >> Android-52-使用URl访问网络资源
  详细解决方案

Android-52-使用URl访问网络资源

热度:291   发布时间:2016-04-28 00:40:21.0
Android---52---使用URl访问网络资源

URL:Uniform Resource Locator 统一资源定位器

 

通常情况而言,URl可以有协议名、主机、端口和资源组成,即满足以下格式:

protocol://host:port/resourceName

 

例如:
http://www.baidu.com/index.php

 

 

Public Constructors 构造方法:

 

 URL(String spec) Creates a new URL instance by parsing the string spec.   URL(URL context, String spec) Creates a new URL to the specified resource spec.   URL(URL context, String spec, URLStreamHandler handler) Creates a new URL to the specified resource spec.   URL(String protocol, String host, String file) Creates a new URL instance using the given arguments.   URL(String protocol, String host, int port, String file) Creates a new URL instance using the given arguments.   URL(String protocol, String host, int port, String file, URLStreamHandler handler) Creates a new URL instance using the given arguments. 


 

常用方法:

 


String getFile ():获取此URL的资源名
String getHost(): 获取主机名
String getPath ():获取路径
int getPort ():获取端口号
String getProtocol ():获取协议名称
String getQuery():获取此URl的查询字符串部分
URLConnection openConnection():返回一个URLConnection对象,它表示到URl所引用的远程对象的连接
InputStream openStream():打开与此URL的连接,并返回一个用于读取该URL资源的输入流

 

 

读取网络资源:

 

一张图片:
/*
http://www.crazyit.org/attachments/month_1008/20100812_7763e970f822325bfb019ELQVym8tW3A.png
*/

两个功能:

1.以上面网址为参数创建URL对象,获得该对象资源的InputStream,使用BitmapFactory.decodeStream()方法解析出图片 并显示

2.将图片下载下来。

 

 

public class MainActivity extends Activity {	ImageView show;	Bitmap bitmap;	Handler handler = new Handler() {		public void handleMessage(android.os.Message msg) {			if (msg.what == 0x123) {				// 使用ImageView显示该图片				show.setImageBitmap(bitmap);			}		};	};	@Override	protected void onCreate(Bundle savedInstanceState) {		super.onCreate(savedInstanceState);		setContentView(R.layout.activity_main);		show = (ImageView) findViewById(R.id.show);		new Thread() {			public void run() {				try {					// 定义一个URL对象					URL url = new URL("http://www.crazyit.org/"							+ "attachments/month_1008/20100812_7763e970f"							+ "822325bfb019ELQVym8tW3A.png");					// 打开该URL对应的资源的输入流					InputStream is = url.openStream();					// 从InputStream中解析图片					bitmap = BitmapFactory.decodeStream(is);					// 发送消息 通知UI组件显示该图片					handler.sendEmptyMessage(0x123);					is.close();									//下载图片					// 再次打开URL对应资源的输入流,创建图片对象					is = url.openStream();					// 打开手机文件对应的输出流					OutputStream os = openFileOutput("crazyit.png",							MODE_WORLD_READABLE);					byte buff[] = new byte[1024];					int hasRead = 0;					// 将图片下载到本地					while ((hasRead = is.read(buff)) > 0) {						os.write(buff, 0, hasRead);					}					is.close();					os.close();				} catch (Exception e) {					// TODO Auto-generated catch block					e.printStackTrace();				}			};		}.start();	}}


 

 

 

  相关解决方案