1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| public class HttpImageUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpImageUtils.class); public static final int TIMEOUT = 5 * 1000;
public static byte[] getNetImgByUrl(String strUrl) { try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(TIMEOUT); InputStream inStream = conn.getInputStream(); return readInputStream(inStream); } catch (Exception e) { logger.error(e.getMessage(),e); } return null; }
private static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[Integer.MAX_VALUE]; int len = 0; while ((len = inStream.read(buffer)) != -1) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } }
|