2

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.

4

2 に答える 2

3

ConnectionTimeoutを5秒に設定し、SocketTimeoutExceptionをキャッチして、そこからToastを表示すると、おそらくより良い解決策になります。ConnectionTimeoutをある値に設定し、接続が応答コードを取得しなかった場合、SocketTimeoutExceptionがスローされます。ここでそれをキャッチし、ハンドラーを呼び出してUIでトーストを表示できます。最後に、接続を閉じてメモリを解放します。

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) 
于 2012-07-24T20:22:03.787 に答える
1

代わりにクラスを使用することを検討してくださいAndroidHttpClient。これには事前に設定された優れたタイムアウトがあるため、何もする必要はありません。

于 2012-07-24T20:45:12.533 に答える