(1)获得网络图片输入流并将之装化为byte数组。
public class ImageService {
public static byte[] getImage(String path) throws Exception {
URL url = new URL(path);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
if(conn.getResponseCode()==200){
InputStream inStream = conn.getInputStream();
return StreamTool.read(inStream);
}
return null;
}
}
其中StreamTool为创建读输入流的工具类
public class StreamTool {
public static byte[] read(InputStream inStream) throws Exception {
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer)) !=-1){
outstream.write(buffer, 0, len);
<span style="white-space:pre"> //String data = StreamTool.read(inStream);
<span style="white-space:pre"> </span>//String html = new String(data,"UTF-8");
<span style="white-space:pre"> </span>//return html;</span>
}
inStream.close();
return outstream.toByteArray();
}
}
(2)用字节数组存储得到的图片的数据,并转化为图片显示出来
public class BttonClickListener implements View.OnClickListener{
String path = pathText.getText().toString();
@Override
public void onClick(View v) { //获得data数据构建图片
try {
byte[] data = ImageService.getImage(path);
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace(); //显示网页源代码
//String html = PageService.getHtml(path)
} }
访问权限<uses-permission android:name="android.perission.INTERNET"/>