①首先要访问互联网那么就要加访问互联网的权限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
②访问互联网其实就是一种流的交换,当点击看出按钮的时候那么程序就是将输入流转换为输出流
代码:
private final class BtnListener implements OnClickListener{ @Override public void onClick(View arg0) { byte[] date; String path=pathEditText.getText().toString(); ImageService service=new ImageService(); try { date =service.seePic(path); Bitmap bitmap=BitmapFactory.decodeByteArray(date, 0, date.length); imageView.setImageBitmap(bitmap); } catch (IOException e) { Toast.makeText(ImageViewActivity.this, "图片加载失败", 1).show(); e.printStackTrace(); } } }
ImageService service=new ImageService();
date =service.seePic(path);
public byte[] seePic(String path) throws IOException { URL url=new URL(path); HttpURLConnection con=(HttpURLConnection)url.openConnection(); con.setConnectTimeout(5000); con.setRequestMethod("GET"); byte[] data=null; if(con.getResponseCode()==200){ InputStream inputStream=con.getInputStream(); data = Utils.read(inputStream); return data; } return null; }
其中:utli
public static byte[] read(InputStream inputStream) throws IOException { byte[] buffer=new byte[1024]; ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream(); int len=0; while((len=inputStream.read(buffer))!=-1){ byteArrayOutputStream.write(buffer, 0, len);//将读到的二进制文件写到内存中 } inputStream.close(); return byteArrayOutputStream.toByteArray(); }
效果图: