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.
常用方法:
该方法用于提取指定URL对应的资源文件名;
该方法返回当前服务器的主机名称;
该函数返回请求路径信息;
该方法返回服务器提供的端口号号码;
该函数用于确定请求所使用的通信协议类型;
该方法提取出包含查询参数的信息片段;
建立与远程服务器之间的通信连接;
打开与目标服务器建立通信后,
请调用read()方法读取文件内容
读取网络资源:
一张图片:
/*
http://www.crazyit.org/attachments/month_1008/20100812_7763e970f822325bfb019ELQVym8tW3A.png
*/
两个功能:
通过以指定网址作为参数建立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();
}
}
全部评论 (0)
还没有任何评论哟~
