1

How do i get the Content-Length of a String[] in java?

Current code:

public static int getLength(String[] sa) {
    int result = 0;
    for (String s : sa)
        result += s.length();
    return result;
}

But an incorrect value is returned therefor the browser doesn't read the whole message body.

DutChen18
  • 1,133
  • 1
  • 7
  • 24
  • 1
    Oh, i'm trying to implement keep-alive in my java HTTP server, wich requires a Content-Length to be specified otherwise the client wouldn't know where to stop reading the document. Using the code i wrote in my question the client doesn't receive the whole message, wich is because the Content-Length supplied by the server is incorrect, i assumed this was because `.length()` doesn't count some bytes, but apparently not. – DutChen18 Dec 15 '15 at 15:49

1 Answers1

0

Nevermind i'm stupid, i needed to add 2 to the result for every \n\r (enter) in the String[]

Here's the final code:

public static int getLength(String[] sa) {
    int result = (sa.length - 1) * 2;
    for (String s : sa)
        result += s.length();
    return result;
}
Abdelhak
  • 8,299
  • 4
  • 22
  • 36
DutChen18
  • 1,133
  • 1
  • 7
  • 24