你好我之前从未使用过HttpResponses,我希望能够在3分钟后断开网络连接,因为用户失去了与网络的连接。是否有完整的代码,我可以看到这样的事情?
答案 0 :(得分:0)
我知道两种可能的方法:
这样的事情:
private DefaultHttpClient httpClient;
// set connection timeout to 1 second
HttpConnectionParams.setConnectionTimeout(httpParameters, 1000);
// set socket timeout to 1 second
HttpConnectionParams.setSoTimeout(httpParameters, 1000);
httpClient = new DefaultHttpClient(httpParameters);
/* === and then, use your httpClient to perform your operations... === */
这样的事情:
// create a handler to load content
private final Runnable loadContent = new Runnable() {
@Override
public void run() {
/* === CALL HTTP AND PROCESS IT HERE === */
// remove the timeout runnable after receiving http response
handler.removeCallbacks(timeoutRunnable);
}
}
// create a handler to handle timeout
private final Runnable timeoutRunnable = new Runnable() {
@Override
public void run() {
handler.sendEmptyMessage(1);
}
};
// create a handler to handle the connection
private final Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 1: // timeout
handler.removeCallbacks(timeoutRunnable);
break;
/* === OTHER MESSAGES TO HANDLE OTHER SITUATIONS === */
}
}
};
// call the connection inside a new thread
private void createNewLoader() {
// create a delayed runnable with a timeout of 1 second
handler.postDelayed(timeoutRunnable, 1000);
// call the content loader
new Thread(loadContent).start();
}
希望它有所帮助。
答案 1 :(得分:0)
请勿使用DefaultHttpClient
,Google已将其弃用,停止支持,并建议使用速度更快的URLConnection。超时处理如下:
// Prepare connection
URL url = new URL(sUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(TIMEOUT);
conn.setReadTimeout(TIMEOUT);