从一个URL下载原始数据,基于byte字节

来源:互联网 发布:java list json 转换 编辑:程序博客网 时间:2024/06/05 14:48
[java] view plaincopy
  1. public static byte[] loadRawDataFromURL(String u) throws Exception {  
  2.         URL url = new URL(u);  
  3.         HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  4.   
  5.         InputStream is = conn.getInputStream();  
  6.         BufferedInputStream bis = new BufferedInputStream(is);  
  7.   
  8.         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
  9.   
  10.         final int BUFFER_SIZE = 2048;  
  11.         final int EOF = -1;  
  12.   
  13.         int c;  
  14.         byte[] buf = new byte[BUFFER_SIZE];  
  15.   
  16.         while (true) {  
  17.             c = bis.read(buf);  
  18.             if (c == EOF)  
  19.                 break;  
  20.   
  21.             baos.write(buf, 0, c);  
  22.         }  
  23.   
  24.         conn.disconnect();  
  25.         is.close();  
  26.   
  27.         byte[] data = baos.toByteArray();  
  28.         baos.flush();  
  29.   
  30.         return data;  
  31.     }  
0 0
原创粉丝点击