易网时代-编程资源站
Welcome
微信登录
首页
/
操作系统
/
Linux
/
Android开发之获取网络数据
Android开发之获取网络数据获取网络图片首先我们需要把界面搭建好
<?xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<LinearLayout
xmlns:android
=
"http://schemas.android.com/apk/res/android"
android:layout_width
=
"fill_parent"
android:layout_height
=
"fill_parent"
android:orientation
=
"vertical"
>
<Button
android:id
=
"@+id/showImageID"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
android:text
=
"@string/btn"
/>
//用来点击事件
<ImageView
android:id
=
"@+id/imageViewID"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
/>
//用来显示图片
</LinearLayout>
接下来我们需要添加ImageService类
package cn.class3g.service;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageService {
public static byte[] getImageData(String path) throws Exception {
URL
url
=
new
URL(path);
HttpURLConnection
conn
= (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
InputStream
inStream
=
conn
.getInputStream();
ByteArrayOutputStream
bos
=
new
ByteArrayOutputStream();
byte[]
buffer
=
new
byte[1024];
int
len
=
0
;
while ((
len
=
inStream
.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
byte[]
data
=
bos
.toByteArray();
return data;
}
}
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图