1、查看网络上的图片
客户端发送http请求至服务器,如果请求成功,响应码为200,服务器会通过流向客户端返回请求的数据
例如:
//按键监听事件
public void click(View v){
String path = "http://localhost:8080/test.jpg";
//发送http请求
try {
URL url = new URL(path);//使用网址构造一个URL对象
//获取连接对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置一些属性
conn.setRequestMethod("GET");//设置请求方式,注意大小写
conn.setConnectTimeout(5000);//设置请求超时
conn.setReadTimeout(5000);//设置读取超时
conn.connect();//发送请求,建立连接
//判断请求是否成功
if(conn.getResponseCode() == 200){
//获取服务器返回的流,流里就是客户端请求的数据
InputStream is = conn.getInputStream();
//读取流里的数据,构造出一张图片
Bitmap bm = BitmapFactory.decodeStream(is);
//将下载的图片显示至imageview
ImageView iv = (ImageView) findViewById(R.id.iv);
iv.setImageBitmap(bm);
}
else{
Toast.makeText(this, "请求失败", 0).show();
}
} catch (Exception e) {
e.printStackTrace();