1 28 29 package HTTPClient; 30 31 import java.io.IOException ; 32 import java.io.EOFException ; 33 import java.io.InputStream ; 34 import java.io.FilterInputStream ; 35 36 37 43 class ChunkedInputStream extends FilterInputStream 44 { 45 48 ChunkedInputStream(InputStream is) 49 { 50 super(is); 51 } 52 53 54 byte[] one = new byte[1]; 55 public synchronized int read() throws IOException 56 { 57 int b = read(one, 0, 1); 58 if (b == 1) 59 return (one[0] & 0xff); 60 else 61 return -1; 62 } 63 64 65 private int chunk_len = -1; 66 private boolean eof = false; 67 68 public synchronized int read(byte[] buf, int off, int len) 69 throws IOException 70 { 71 if (eof) return -1; 72 73 if (chunk_len == -1) { 75 try 76 { chunk_len = Codecs.getChunkLength(in); } 77 catch (ParseException pe) 78 { throw new IOException (pe.toString()); } 79 } 80 81 if (chunk_len > 0) { 83 if (len > chunk_len) len = chunk_len; 84 int rcvd = in.read(buf, off, len); 85 if (rcvd == -1) 86 throw new EOFException ("Premature EOF encountered"); 87 88 chunk_len -= rcvd; 89 if (chunk_len == 0) { 91 in.read(); in.read(); chunk_len = -1; 94 } 95 96 return rcvd; 97 } 98 else { 100 Request dummy = 102 new Request(null, null, null, null, null, null, false); 103 new Response(dummy, null).readTrailers(in); 104 105 eof = true; 106 return -1; 107 } 108 } 109 110 111 public synchronized long skip(long num) throws IOException 112 { 113 byte[] tmp = new byte[(int) num]; 114 int got = read(tmp, 0, (int) num); 115 116 if (got > 0) 117 return (long) got; 118 else 119 return 0L; 120 } 121 122 123 public synchronized int available() throws IOException 124 { 125 if (eof) return 0; 126 127 if (chunk_len != -1) 128 return chunk_len + in.available(); 129 else 130 return in.available(); 131 } 132 } 133 134 | Popular Tags |