2013-07-18 33 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; 
    } 
} 

}