That last line it blows up with the error: Server returned HTTP response code: 500.
I don't think the problem is with the server I am connecting. This code works most of the time.
Since the response code "500" is the http status code for an "internal server error", I'd say the problem isn't in the code you've shown us. It could be with the data you are sending, but without looking at the server code and logs I don't think we have enough information to help you at this point.