public class ImageService { /** * 获取图片 * @param path 网络图片路径 * @return 图片的字节数据 */ public static byte[] getImage(String path) throws Exception{ URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时时间 conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); if(conn.getResponseCode()==200){ InputStream inStream = conn.getInputStream(); byte[] data = StreamTool.read(inStream); return data; } return null; } }
<span style="FONT-WEIGHT: normal">public class StreamTool { /** * 读取输入流数据 * @param inStream * @return */ 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); } inStream.close(); return outStream.toByteArray(); } }