我正在使用HTTPUrlConnection连接到一个简单的RSS提要.它完美地运作.我想在连接中添加超时,因为我不希望我的应用程序在连接错误或其他情况下挂起.这是我使用的代码,setConnectTimeout方法没有任何效果.
HttpURLConnection http = (HttpURLConnection) mURL.openConnection();
http.setConnectTimeout(15000); //timeout after 15 seconds
...
Run Code Online (Sandbox Code Playgroud)
如果它有助于我在android上开发.
pap*_*pap 60
您应该尝试设置读取超时(http.setReadTimeout()).通常情况下,Web服务器会很乐意接受您的连接,但实际响应请求可能会很慢.
Can*_*ner 18
您可能要么/两个:
1)不要从连接
2中读取任何内容.不要正确捕获和处理异常
如前所述这里,使用类似的逻辑是:
int TIMEOUT_VALUE = 1000;
try {
URL testUrl = new URL("http://google.com");
StringBuilder answer = new StringBuilder(100000);
long start = System.nanoTime();
URLConnection testConnection = testUrl.openConnection();
testConnection.setConnectTimeout(TIMEOUT_VALUE);
testConnection.setReadTimeout(TIMEOUT_VALUE);
BufferedReader in = new BufferedReader(new InputStreamReader(testConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
answer.append(inputLine);
answer.append("\n");
}
in.close();
long elapsed = System.nanoTime() - start;
System.out.println("Elapsed (ms): " + elapsed / 1000000);
System.out.println("Answer:");
System.out.println(answer);
} catch (SocketTimeoutException e) {
System.out.println("More than " + TIMEOUT_VALUE + " elapsed.");
}
Run Code Online (Sandbox Code Playgroud)
我遇到了类似的问题 - 因为HttpUrlConnection不会在下载过程中超时.例如,如果您在下载时关闭wifi,我的继续说它正在下载,卡在相同的百分比.
我找到了一个使用TimerTask连接到名为DownloaderTask的AsyncTask的解决方案.尝试:
class Timeout extends TimerTask {
private DownloaderTask _task;
public Timeout(DownloaderTask task) {
_task = task;
}
@Override
public void run() {
Log.w(TAG,"Timed out while downloading.");
_task.cancel(false);
}
};
Run Code Online (Sandbox Code Playgroud)
然后在实际的下载循环中设置一个超时错误的计时器:
_outFile.createNewFile();
FileOutputStream file = new FileOutputStream(_outFile);
out = new BufferedOutputStream(file);
byte[] data = new byte[1024];
int count;
_timer = new Timer();
// Read in chunks, much more efficient than byte by byte, lower cpu usage.
while((count = in.read(data, 0, 1024)) != -1 && !isCancelled()) {
out.write(data,0,count);
downloaded+=count;
publishProgress((int) ((downloaded/ (float)contentLength)*100));
_timer.cancel();
_timer = new Timer();
_timer.schedule(new Timeout(this), 1000*20);
}
_timer.cancel();
out.flush();
Run Code Online (Sandbox Code Playgroud)
如果它超时,并且在20秒内不会下载1K,它取消而不是看起来永远下载.
| 归档时间: |
|
| 查看次数: |
75256 次 |
| 最近记录: |