java - How to read http request properly? -
how read http request using inputstream? used read this:
inputstream in = address.openstream(); bufferedreader reader = new bufferedreader(new inputstreamreader(in)); stringbuilder result = new stringbuilder(); string line; while((line = reader.readline()) != null) { result.append(line); } system.out.println(result.tostring());
but reader.readline()
blocked, because there no guarantee null
line reached. of course can read content-length header , read request in loop:
for (int = 0; < contentlength; i++) { int = br.read(); body.append((char) a); }
but if content-length set big(i guess set manually purpose), br.read()
blocked. try read bytes directly inputstream this:
byte[] bytes = getbytes(is); public static byte[] getbytes(inputstream is) throws ioexception { int len; int size = 1024; byte[] buf; if (is instanceof bytearrayinputstream) { size = is.available(); buf = new byte[size]; len = is.read(buf, 0, size); } else { bytearrayoutputstream bos = new bytearrayoutputstream(); buf = new byte[size]; while ((len = is.read(buf, 0, size)) != -1) bos.write(buf, 0, len); buf = bos.tobytearray(); } return buf; }
but waits forever. do?
if implementing http server should detect end of request according http specification. wiki - https://en.wikipedia.org/wiki/hypertext_transfer_protocol
first of all, should read request line, single line. read request headers. read them until have empty line (i.e. 2 line endings - <cr><lf>
).
after have status line , headers should decide need read body or no because not requests might have body - summary table
then, if need body, should parse headers (which got) , content-length. if - read many bytes stream specified. when content-length missing length determined in other ways. chunked transfer encoding uses chunk size of 0 mark end of content. identity encoding without content-length reads content until socket closed.
Comments
Post a Comment