Eri*_*wne 10 android httpurlconnection
我使用HttpURLConnection的Android的奇巧一些POST数据到服务器.服务器需要很长时间才能响应,并且连接在超时前静默重试1到3次.我不希望它重试,因为服务器处理所有请求,导致Bad Things(TM).
我System.setProperty("http.keepAlive", "false")在打开连接之前尝试过,但这没有用.
Implement a hard timeout yourself, and force close the HttpURLConnection by calling disconnect. This can be done from your Activity using android handler; If you use AsyncTask, you can simply call cancel or Thread.interrupt():
new Handler().postDelayed(new Runnable() {
public void run() {
httpUrlConnTask.cancel(true);
}
}, timeout * 1000);
Run Code Online (Sandbox Code Playgroud)
And in your httpUrlConnTask, call disconnect:
if (isCancelled()) {
urlConnection.disconnect();
return;
}
Run Code Online (Sandbox Code Playgroud)
You may have to do urlConnection in another internal child thread so you can do a while loop in asynctask monitoring for isCancelled. And a try..catch so you can close all the streams properly.
you already have keepAlive false, and readTimeout, consider adding connection timeout too. This will set the socket timeout.
| 归档时间: |
|
| 查看次数: |
4242 次 |
| 最近记录: |