开发者

Reading HTTP Messages in Java

First of all, I'll admit this is a school project, so I need more of just direction, rather than actual code. Also, I cannot use the java.net.HTTPURLConnection and java.net.URL classes to help out...

Ok... I'm creating a HTTP server in Java, but having trouble reading HTTP messages. I need to allow persistent connections (when using HTTP/1.1 and no Connection: close), which is already working. But because of the persistence, there might be multiple requests coming down the pipeline.

I know I can use the Content-Length header to determine how long the message body will be, in bytes. After that, the next message will come down the pipe.

My questions...

  • Should I read in the message byte by byte or char by char, or can I read in line by line? Going line by line would be fine until hitting the message body...
  • Should the message body be saved in byte format, or is String ok (I know HTML is fine, but will images, etc. b开发者_JS百科reak if going through a String?)
  • Is there a scanner that will let me read line by line, and then when I hit the message body, call a getBytes( contentLength ), and it gives me the body?

Thanks again!

Edit: I do not have to support chunked or compressed data.


I suggest reading into byte-arrays. And don't read line wise, but read in chunks of bytes (you can try to use content-length as your chunk size. Beware that read(byte[]) returns the number of bytes actually read and you still may have to call it several times).

Also beware of chunked encoding, although I admit that I do not know whether servers must support this since I always just cared for coding clients.


I second yankee's opinion - at the lower level you should read into a byte array. This will allow you to work both with html and images. At a higher level, you can always convert the html pieces into strings with a specific encoding. You are better off choosing your encoding at the higher level, not the lower one.

Use a buffer and fill it every time with new bytes. As yankee said, you'll need to repeat the calls to read method and check the return value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜