问题
I'm using HttpURLConnection on Android KitKat to POST some data to a server. The server takes a long time to respond, and the connection is silently retrying 1 to 3 times before timing out. I don't want it to retry, since the server acts on all of the requests, resulting in Bad Things(TM).
I've tried System.setProperty("http.keepAlive", "false") before opening the connection, but that doesn't help.
回答1:
For POST calls set
httpURLConnection.setChunkedStreamingMode(0);
and this should fix the silent retries. The bug report and workaround can be found here.
回答2:
Implement a hard timeout yourself, and force close the
HttpURLConnectionby calling disconnect. This can be done from yourActivityusing android handler; If you useAsyncTask, you can simply callcancelorThread.interrupt():new Handler().postDelayed(new Runnable() { public void run() { httpUrlConnTask.cancel(true); } }, timeout * 1000);And in your
httpUrlConnTask, calldisconnect:if (isCancelled()) { urlConnection.disconnect(); return; }You may have to do
urlConnectionin another internal child thread so you can do awhileloop in asynctask monitoring forisCancelled. And atry..catchso you can close all the streams properly.you already have
keepAlivefalse, andreadTimeout, consider adding connection timeout too. This will set the socket timeout.
回答3:
You need to set System.setProperty("sun.net.http.retryPost", "false")
回答4:
Android’s HTTP Clients
Prior to Froyo, HttpURLConnection had some frustrating bugs. In particular, calling close() on a readable InputStream could poison the connection pool. Work around this by disabling connection pooling:
private void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
System.setProperty("http.keepAlive", "false");
}
}
来源:https://stackoverflow.com/questions/24417817/stopping-silent-retries-in-httpurlconnection