1.大框架(简单界面)
button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new Thread() { @Override public void run() { byte[] a = new byte[0]; // 获取图片数据 try { a = Imageservice.getImgae(editText.getText().toString()); } catch (IOException e) { e.printStackTrace(); } Bitmap bitmap = BitmapFactory.decodeByteArray(a, 0, a.length);//数据转化为图片 Message message = Message.obtain(); message.what = 0x11; handler.sendMessage(message); message.obj = bitmap; } }.start(); } }); handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0x11) { imageView.setImageBitmap((Bitmap) msg.obj); } } };
2.Imageservice类
public static byte[] getImgae(String string) throws IOException { URL url = new URL(string); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 基于HTTP协议的连接对象 conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); InputStream inputstream = conn.getInputStream(); try { return StreamTool.readData(inputstream); // 读取流中数据并返回 // 下列操作获取源码 /*String html=new String(StreamTool.readData(inputstream),"UTF-8"); return html;*/ } catch (Exception e) { e.printStackTrace(); } return null; }
3.SteamTool工具类(负责从流中读取数据)
public class StreamTool { public static byte[] readData(InputStream inputstream) throws Exception { ByteArrayOutputStream bb = new ByteArrayOutputStream(); //可以捕获内存缓冲区的数据,转换成字节数组。 byte[] b = new byte[1024]; int len = 0; while ((len = inputstream.read(b, 0, b.length)) != -1) { bb.write(b, 0, len); } return bb.toByteArray(); 获取内存缓冲中的数据 } }