2012-07-09 26 views
5

Ich versuche Verwendung von setConnectTimeout Funktion wie folgt zu erhalten:HttpUrlConnection setConnectTimeout funktioniert nicht?

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; 
} 

und dann:

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(); 
    } 
} 

aber es wird nie in der "catch (SocketTimeoutException socketTimeoutException)" Block. Was ist hier falsch?

P.S. Zum Testen habe ich eine Seite erstellt, die meinen Server für 10 Sekunden in den Ruhezustand versetzt.

Antwort

8

versuchen Sie dies:

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(); 
} 
+0

In Ordnung! Es scheint zu funktionieren, wird aber nicht con.setRequestMethod ("HEAD"); etwas vermasseln? – user1462299

+0

Wie ich aufgrund dieser Zeile angenommen habe, konnten normale Links nicht geladen werden. Ich habe dieses einfach entfernt und conn.connect() hinzugefügt; Es löst jetzt eine IOException-Ausnahme aus, nachdem das Zeitlimit abgelaufen ist. Ich weiß nicht, ob es eine IOException oder etwas anderes ist, außer es funktioniert – user1462299

+0

Es scheint, dass das Timeout nicht funktioniert, wenn das Netzwerk während des Downloads getrennt wird. – NoBugs

Verwandte Themen