예제 #1
0
 public static MessageHeader readHeader(InputStream in)
     throws IOException, MessageFormatException {
   int match = 0;
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   int i;
   try {
     do {
       i = in.read();
       if (i == -1) {
         if (out.size() > 0)
           throw new MessageFormatException("Unexpected end of stream", out.toByteArray());
         return null;
       }
       out.write(i);
       if (i == CRLF[match % 2]) match++;
     } while (match < 4);
   } catch (IOException e) {
     if (out.size() > 0)
       throw new MessageFormatException("Incomplete message header", e, out.toByteArray());
     throw e;
   }
   MutableMessageHeader header = new MutableMessageHeader.Impl();
   header.setHeader(out.toByteArray());
   return header;
 }
예제 #2
0
  public static boolean flushContent(MutableMessageHeader header, InputStream in, OutputStream out)
      throws MessageFormatException, IOException {
    boolean read = false;
    String te = header.getHeader(TRANSFER_ENCODING);
    if (CHUNKED.equalsIgnoreCase(te)) {
      in = new ChunkedInputStream(in);
    } else if (te != null) {
      throw new IOException("Unknown Transfer-Encoding '" + te + "'");
    } else {
      String cl = header.getHeader(CONTENT_LENGTH);
      if (cl != null) {
        try {
          int l = Integer.parseInt(cl.trim());
          if (l == 0) return read;
          in = new FixedLengthInputStream(in, l);
        } catch (NumberFormatException nfe) {
          throw new MessageFormatException("Invalid Content-Length header: " + cl, nfe);
        }
      }
    }
    byte[] buff = new byte[2048];
    int got;
    while ((got = in.read(buff)) > 0) {
      read = true;
      if (out != null) out.write(buff, 0, got);
    }

    return read;
  }