获取URL的地址:URLurl=newURL(path);然后通过ur" />
文档库 最新最全的文档下载
当前位置:文档库 › 从网络中获取数据然后显示在ImageView

从网络中获取数据然后显示在ImageView

从网络中获取图片然后显示在MainActivity的ImageView上面
(Tip:首先在配置文件中添加网络访问权限:
)
首先在main.xml中创建一个ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image"
/>
获取URL的地址:
URL url = new URL(path);
然后通过url创建一个HttpURLConnection连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5 * 1000);
设置请求方法和响应时间
当响应码为200的时候,获取连接的资源.
然后把资源转换成一个字节数据
if (connection.getResponseCode() == 200)
{
InputStream inputStream = connection.getInputStream();
byte[] data = StreamTool.getInputStream(inputStream);
return data;
}
解析输入流然后返回一个字节数组的方法
public static byte[] getInputStream(InputStream inputStream) throws Throwable
{
byte[] buff = new byte[1024];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int len = 0;
while ((len = inputStream.read(buff)) != -1)
{
outputStream.write(buff, 0, len);
}
inputStream.close();
return outputStream.toByteArray();
}
(
创建一个长度为1024字节数组.
然后当输入流不为空的时候,从输入流中读取.
然后把数据写入:一个字节数组输入流中...
最后放回成一个字节数组的方式...
)

相关文档