Always check your byte count when using Java Input Streams.
Why do you ask, Mr. intelligent internet reader?
Well, the other day I ran across a strange response with some of our client code. In some rare instances, maybe 1 in 500 requests, the HTTP response we received from our server would come back as a bunch of unreadable mess.
When looking into the problem closer, we found out that in a small subset of requests, the server was indeed sending a response back, but the response was completely unreadable.
Tracking down these kinds of problems are really painful. First we had to figure out if the problem was somehow with our decoding techniques. Nope, that checked out all right. Then we looked into the possibility of the server sending back bad info in some situations. Nope. After 1000s of attempts, everything checked out fine.
So I went back to check out the client code. I then looked toward what was happening before the response was decoded. Even there , everything looked fine. X amount of bytes were received from the server via simple Java Input Stream. But wait, the number of bytes were a bit low, about 5 bytes short. This was happening in every response. Only sometimes it would cause the response to be unreadable. What would cause that?
After a few hours of working with the code, it turns out that a simple Java byte array does not correctly convert over to a standard byte array. Instead of using the standard byte array, the ByteArrayInput Stream needs to be used to convert to a byte array. After we added this simple one line fix, everything checked out!
So the bottom line is really…
Never assume your response from a server is completely correct until you know the byte count is spot on. And always be weary of Java Input Streams.