public InputStream getFileStream(String uri){ BufferedInputStream bin = null; ByteArrayOutputStream out = null; ByteArrayInputStream inputStream = null; try { out = new ByteArrayOutputStream(); URL url = new URL(uri); HttpURLConnection c = (HttpURLConnection) url.openConnection(); c.setRequestMethod("GET"); c.setRequestProperty("Charset", "UTF-8"); bin = new BufferedInputStream(c.getInputStream()); int size = 0; int len = 0; byte[] buf = new byte[1024]; while ((size = bin.read(buf)) != -1) { len += size; out.write(buf, 0, size); } inputStream = new ByteArrayInputStream(out.toByteArray()); }catch (Exception e){ logger.error("[Error] get file failed!"); }finally { if( bin!= null){ try{ bin.close(); }catch (IOException e){ logger.error("close stream error!"); } } if( out != null){ try{ bin.close(); }catch (IOException e){ logger.error("close stream error!"); } } if( inputStream != null){ try{ bin.close(); }catch (IOException e){ logger.error("close stream error!"); } } } return inputStream; }
特别提示,httpURLConnection类引的是sun公司的包,不要错引为apache的,引了apache的不会报错,但是拿不到返回流!切记切记!