I'm trying to get use of setConnectTimeout function like this:
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;
}
and then:
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();
}
}
However, it never gets in the "catch (SocketTimeoutException socketTimeoutException)" block. What's wrong here.
P.S. For the testing I've made a page that puts my server into sleep for 10 seconds.
try this:
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With