A Merz
A Merz

Reputation: 25

HTTP Server issues

Hi guys i have a very basic http server coded in about 30 minutes for an assignment and have come across a very weird problem. We were specified to use only BufferedOutputStream instead of a StreamWriter as there is apparently an issue with using PrintWriters as they perform differently on different platforms. I am confused as i have the follwoing println method...

private void println(BufferedOutputStream bos, String s) throws IOException {
    String toPrint = s + "\r\n";
    byte[] array = toPrint.getBytes();
    for (int i = 0; i < array.length; i++) {
        bos.write(array[i]);
    }
    return;
}

I am confused as when using

println(outStream,"HTTP/1.1 200 OK");
println(outStream,"");
println(outStream,"Hello World");

the webpage says i have not sent any data but using...

writer.println("HTTP/1.1 200 OK");
writer.println("");
writer.println("Hello World");

everything appears perfectly.. ive tried a few things such as flushing the outStstream but i dont understand why it wont work

Thanks for the help

Upvotes: 0

Views: 68

Answers (2)

user207421
user207421

Reputation: 310916

private void println(BufferedOutputStream bos, String s) throws IOException {
    String toPrint = s + "\r\n";
    byte[] array = toPrint.getBytes();
    for (int i = 0; i < array.length; i++) {
        bos.write(array[i]);
    }
    return;
}

You don't need all that. In fact you don't need any of it. Just call bos.write((s+"\r\n").getBytes()) directly from wherever you're calling it, and then flush it when you've written everything you need to write.

Note that in HTTP 1.1 you either have to close the BufferedOutputStream or provide a Content-length header (or use chunked transfer encoding).

Upvotes: 0

Abacus
Abacus

Reputation: 19431

Have you flushed and closed your BufferedOutputStream after writing all the data?

Upvotes: 1

Related Questions