Reputation: 7266
I am working on an Android app that needs to read a line from a web page right when it starts. I am doing this with the following code:
try{
URL url = new URL("http://www.example.com");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
line = reader.readLine();
}
catch(Exception e){
e.printStackTrace();
}
It is working fine, but sometimes the connection or the server are slow, and the app freezes or crashes.
I want to put a timeout of 5 seconds, and should it reach that timeout I want to show a toast to the user saying the network is busy, asking him to try again later.
I tried the HttpURLConnection setConnectTimeout() method but it didn't work.
Any clues how I can achieve this? Thanks forehand.
Upvotes: 2
Views: 8841
Reputation: 4214
Probably better solution if you setConnectionTimeout to 5 sec, catch SocketTimeoutException and show Toast from there. When you set ConnectionTimeout to some value and connection didn't get response code will throw SocketTimeoutException. Here you can catch it and call handler to show a toast in UI. Finally will close the connection and release memory.
class MyHttpClient extends DefaultHttpClient {
@Override
protected ClientConnectionManager createClientConnectionManager() {
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https",
mSSLSocketFactory != null
? mSSLSocketFactory
: SSLSocketFactory.getSocketFactory(),
443));
return new SingleClientConnManager(getParams(), registry);
}
MyHttpClient httpClient = new MyHttpClient();
// set http params
HttpParams params = httpClient.getParams();
params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(30000));
params.setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(30000));
httpClient.setParams(params);
....
httpClient.execute(httpUriRequest)
Upvotes: 3
Reputation: 48232
Consider using AndroidHttpClient
class instead, it has nice preset timeouts so you wouldn't have to do anything.
Upvotes: 1