我正在尝试像这样使用 setConnectTimeout 函数:
protected HttpURLConnection getConnection() throws SocketTimeoutException, IOException{
Log.d("HTTPRequest", address);
URL page = new URL(address);
HttpURLConnection connection = (HttpURLConnection) page.openConnection();
connection.setUseCaches(cacheResult);
connection.setConnectTimeout(3000);
connection.connect();
return connection;
}
进而:
public String getTextData() throws InternetConnectionUnavailableException {
try{
HttpURLConnection conn = getConnection();
StringBuffer text = new StringBuffer();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;
while (true) {
if((line = buff.readLine()) != null){
text.append(line);
}else{
break;
}
}
return (text.toString());
} catch (SocketTimeoutException socketTimeoutException) {
throw new InternetConnectionUnavailableException();
} catch (IOException ioException) {
throw new InternetConnectionUnavailableException();
}
}
但是,它永远不会进入“catch (SocketTimeoutException socketTimeoutException)”块。这里有什么问题。
PS 对于测试,我制作了一个页面,让我的服务器进入睡眠状态 10 秒。