1 32 package com.imagero.uio.buffer; 33 34 import com.imagero.uio.io.IOutils; 35 36 import java.io.IOException ; 37 import java.io.InputStream ; 38 import java.net.HttpURLConnection ; 39 import java.net.URL ; 40 41 50 public class HTTPBuffer implements Buffer { 51 52 URL url; 53 54 long offset; 55 int length; 56 byte[] data; 57 58 public HTTPBuffer(URL url, int offset, int length) { 59 this.url = url; 60 this.offset = offset; 61 this.length = length; 62 63 } 67 68 75 public byte[] getData() throws IOException { 76 if(data == null) { 77 readData(); 78 } 79 return data; 80 } 81 82 public byte[] getData(byte[] d) throws IOException { 83 if(data == null) { 84 readData(); 85 } 86 System.arraycopy(data, 0, d, 0, Math.min(data.length, d.length)); 87 return d; 88 } 89 90 public int length() { 91 return length; 92 } 93 94 private void readData() throws IOException { 95 HttpURLConnection httpcon = (HttpURLConnection ) url.openConnection(); 96 httpcon.setAllowUserInteraction(true); 97 httpcon.setDoInput(true); 98 httpcon.setDoOutput(true); 99 httpcon.setRequestMethod("GET"); 100 httpcon.setUseCaches(false); 101 httpcon.setRequestProperty("Range", "bytes=" + offset + "-" + (offset + length)); 102 httpcon.connect(); 103 104 String responseMessage = httpcon.getResponseMessage(); 105 int responseCode = httpcon.getResponseCode(); 106 if(responseCode != 206) { 107 httpcon.disconnect(); 108 throw new IOException ("byteserving not supported by server"); 109 } 110 111 InputStream in = httpcon.getInputStream(); 113 114 data = new byte[length]; 115 IOutils.readFully2(in, data); 116 117 httpcon.disconnect(); 118 } 119 120 public boolean isDirty() { 121 return false; 122 } 123 } 124 | Popular Tags |