我正试图像这样使用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)”块。这里有什么不对。
P.S。为了测试我已经制作了一个让我的服务器进入睡眠状态10秒的页面。
答案 0 :(得分:8)
试试这个:
try {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
con.setConnectTimeout(5000); //set timeout to 5 seconds
con.setReadTimeout(socketTimeout);
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
} catch (java.net.SocketTimeoutException e) {
e.printStackTrace();
} catch (java.io.IOException e) {
e.printStackTrace();
}