1 13 14 package com.go.trove.net; 15 16 import java.io.*; 17 18 24 public class HttpUtils { 25 34 public static String readLine(InputStream in, byte[] buffer) 35 throws IllegalArgumentException , IOException 36 { 37 return readLine(in, buffer, -1); 38 } 39 40 50 public static String readLine(InputStream in, byte[] buffer, int limit) 51 throws IllegalArgumentException , IOException, LineTooLongException 52 { 53 if (!in.markSupported()) { 54 throw new IllegalArgumentException 55 ("InputStream doesn't support marking: " + in.getClass()); 56 } 57 58 String line = null; 59 60 int cursor = 0; 61 int len = buffer.length; 62 63 int count = 0; 64 int c; 65 loop: 66 while ((c = in.read()) >= 0) { 67 if (limit >= 0 && ++count > limit) { 68 throw new LineTooLongException(limit); 69 } 70 71 switch (c) { 72 case '\r': 73 in.mark(1); 74 if (in.read() != '\n') { 75 in.reset(); 76 } 77 case '\n': 79 if (line == null && cursor == 0) { 80 return ""; 81 } 82 break loop; 83 default: 84 if (cursor >= len) { 85 if (line == null) { 86 line = new String (buffer, "8859_1"); 87 } 88 else { 89 line = line.concat(new String (buffer, "8859_1")); 90 } 91 cursor = 0; 92 } 93 buffer[cursor++] = (byte)c; 94 } 95 } 96 97 if (cursor > 0) { 98 if (line == null) { 99 line = new String (buffer, 0, cursor, "8859_1"); 100 } 101 else { 102 line = line.concat(new String (buffer, 0, cursor, "8859_1")); 103 } 104 } 105 106 return line; 107 } 108 109 118 public static String readLine(InputStream in, char[] buffer) 119 throws IllegalArgumentException , IOException 120 { 121 return readLine(in, buffer, -1); 122 } 123 124 134 public static String readLine(InputStream in, char[] buffer, int limit) 135 throws IllegalArgumentException , IOException, LineTooLongException 136 { 137 if (!in.markSupported()) { 138 throw new IllegalArgumentException 139 ("InputStream doesn't support marking: " + in.getClass()); 140 } 141 142 String line = null; 143 144 int cursor = 0; 145 int len = buffer.length; 146 147 int count = 0; 148 int c; 149 loop: 150 while ((c = in.read()) >= 0) { 151 if (limit >= 0 && ++count > limit) { 152 throw new LineTooLongException(limit); 153 } 154 155 switch (c) { 156 case '\r': 157 in.mark(1); 158 if (in.read() != '\n') { 159 in.reset(); 160 } 161 case '\n': 163 if (line == null && cursor == 0) { 164 return ""; 165 } 166 break loop; 167 default: 168 if (cursor >= len) { 169 if (line == null) { 170 line = new String (buffer); 171 } 172 else { 173 line = line.concat(new String (buffer)); 174 } 175 cursor = 0; 176 } 177 buffer[cursor++] = (char)c; 178 } 179 } 180 181 if (cursor > 0) { 182 if (line == null) { 183 line = new String (buffer, 0, cursor); 184 } 185 else { 186 line = line.concat(new String (buffer, 0, cursor)); 187 } 188 } 189 190 return line; 191 } 192 } 193 | Popular Tags |