2013-07-18 34 views
-1

如果手機無法聯繫服務器,我該如何設置超時時間? 背後的原因是我有一個加載對話框不斷旋轉,我想連接10秒後放棄,這將關閉加載對話框。android java http timeout不工作

public class GetResults { 
String data = null; 
String URLME = null; 
String Search = null; 
BufferedReader inn; 

@SuppressWarnings("finally") 
public String GetLocationData(String THESEARCHSTRING) throws Exception { 
    Search = THESEARCHSTRING; 
    try { 
     URL site = new URL("http://www.google.com/"); 
     java.net.URLConnection yc = site.openConnection(); 
     inn = new BufferedReader(new InputStreamReader(yc.getInputStream())); 
     StringBuffer sb = new StringBuffer(""); 
     String l = ""; 
     String ln = System.getProperty("line.separator"); 
     while ((l = inn.readLine()) != null) { 
      sb.append(l + ln); 
     } 
     inn.close(); 

     data = sb.toString(); 
     URLME = data; 
     return URLME; 
    } finally { 
     if (inn != null) { 
      try { 
       inn.close(); 
       return URLME; 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     return URLME; 
    } 
} 

}

+0

得到它NVM yc.setConnectTimeout(5000); \t \t \t yc.setReadTimeout(10000); – Xjasz

+0

當你甚至沒有設置一個標題爲「暫停不工作」的問題時,發佈這個問題是完全不合理的。 -1 – EJP

回答

0

請儘量使用和檢查做增加超時時間。

import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL;

public class c static String data = null; static String URLME = null; static String Search = null; static BufferedReader inn;

@SuppressWarnings("finally") 
public static String GetLocationData(String THESEARCHSTRING) 
     throws Exception { 
    Search = THESEARCHSTRING; 
    try { 
     URL site = new URL("http://www.google.com/"); 
     java.net.URLConnection yc = site.openConnection(); 
     yc.setConnectTimeout(1); 
     inn = new BufferedReader(new InputStreamReader(yc.getInputStream())); 
     StringBuffer sb = new StringBuffer(""); 
     String l = ""; 
     String ln = System.getProperty("line.separator"); 
     while ((l = inn.readLine()) != null) { 
      sb.append(l + ln); 
     } 
     inn.close(); 

     data = sb.toString(); 
     URLME = data; 
     return URLME; 
    } finally { 
     if (inn != null) { 
      try { 
       inn.close(); 
       return URLME; 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     return URLME; 
    } 
} 

}