For everyone who is faced with this problem, I had an order of operations that affected me only when I was doing HTTP POST, which had content in the request body. This is not entirely clear in all scenarios when the HttpURLConnection actually initiates a connection to the server.
My initial request looked like this:
HttpURLConnection conn = null; try { conn = (HttpURLConnection) baseUrl.openConnection(); conn.setConnectTimeout(connectTimeoutMillis); conn.setReadTimeout(requestTimeoutMillis);
It turns out you cannot call βconn.setRequestMethod (...)β after you called βconn.getOutputStream ()β, so in my case, a simple fix was calling βconn.setRequestMethod (...)β before than contact a letter to the requesting authority. Work code:
HttpURLConnection conn = null; try { conn = (HttpURLConnection) baseUrl.openConnection(); conn.setConnectTimeout(connectTimeoutMillis); conn.setReadTimeout(requestTimeoutMillis); //required for reading a response body conn.setDoInput(true); try { conn.setRequestMethod(verb.toUpperCase()); } catch (final ProtocolException e) { response.setError("Invalid HTTP verb \"" + verb + "\" received.",""); Log.e(TAG, response.errorMessage, e); return response; } //Not all request types have a body (eg GET usually doesn't) if(requestBody != null && requestBody.length > 0) { conn.setDoOutput(true); conn.setFixedLengthStreamingMode(requestBody.length); conn.getOutputStream().write(requestBody); conn.getOutputStream().flush(); conn.getOutputStream().close(); }
The only real change is simply switching the order of the calls and eliminating the exception. Hope this solves the problem for everyone who has this problem.
source share