对于遇到此问题的其他任何人,我遇到了一个操作顺序问题,该问题仅在我执行请求正文中包含内容的 HTTP POST 时才影响到我。当 HttpURLConnection 实际启动与服务器的连接时,在所有情况下并不完全清楚。
我最初的请求如下所示:
HttpURLConnection conn = null;
try
{
conn = (HttpURLConnection) baseUrl.openConnection();
conn.setConnectTimeout(connectTimeoutMillis);
conn.setReadTimeout(requestTimeoutMillis);
//required for reading a response body
conn.setDoInput(true);
//Not all request types have a body (e.g. 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();
}
try
{
conn.setRequestMethod(verb.toUpperCase());
}
catch (final ProtocolException e)
{
response.setError("Invalid HTTP verb \"" + verb + "\" received.","");
Log.e(TAG, response.errorMessage, e);
return response;
}
事实证明,在你调用“conn.getOutputStream()”之后你不能调用“conn.setRequestMethod(...)”,所以在我的例子中,简单的修复是调用“conn.setRequestMethod(...) " 在处理写入请求正文之前。工作代码是:
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 (e.g. 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();
}
唯一真正的变化只是切换调用的顺序,这样就消除了异常。希望这可以解决其他遇到此问题的人的问题。