I think your problem is that you open the input stream before you write and close the output stream. Of course, the Sun Tutorial does just that.
If you quickly open the input stream, it is possible that the output stream will be closed automatically, as a result of which the server will see an empty POST request. This may be enough to make him confused and send a 500 response.
Even if this is not what causes 500 errors, it is a good idea to do things in the order shown in the tutorial. To begin with, if you accidentally read the answer before you finish writing the request, you will most likely (at least temporarily) block the connection. (Actually, it looks like your code is doing this because you are not closing the record before reading from the reader.)
A separate problem is that your code does not close the connection under any circumstances and, therefore, network connections may leak. If he does this repeatedly, it will most likely lead to more IOExceptions.
Stephen c
source share