2011-07-26 36 views
0

我正在使用以下两个函数从服务器下载字符串。我也记录了下载文本所需的时间,无论是客户端还是服务器都可以看到。下载的字符串从不相同。下载字符串时超时

服务器时间只有几毫秒,但客户端看到的时间平均为100毫秒,具体取决于wifi信号。有时候,即使服务器时间仍在可接受的范围内,客户端时间也会上升到3000毫秒(但从不高于3200毫秒)。

我开始认为超时是在某处定义的,但我不知道它在哪里。这不在我的代码中,我在开发者网站和谷歌环顾四周,没有结果。

我希望有人可以给我一些线索,可以定义这种延迟,并确认它默认为3000毫秒。

private String DownloadText(String URL) 
{ 
    String str = ""; 
    int BUFFER_SIZE = 2000; 
    InputStream in = null; 
    try{ 
     in = OpenHttpConnection(URL); 
    } catch (IOException e1) { 
     e1.printStackTrace(); 
     return ""; 
    } 
    catch(ArithmeticException ae){ 
     // 
    } 
    try{ 
     InputStreamReader isr = new InputStreamReader(in); 
     int charRead; 

      char[] inputBuffer = new char[BUFFER_SIZE];   
     try { 
      while ((charRead = isr.read(inputBuffer))>0) 
      {      
       //---convert the chars to a String--- 
       String readString = 
        String.copyValueOf(inputBuffer, 0, charRead);      
       str += readString; 
       inputBuffer = new char[BUFFER_SIZE]; 
      } 
      in.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return ""; 
     } 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    return str;   
} 

private InputStream OpenHttpConnection(String urlString) throws IOException { 
    InputStream in = null; 
    int response = -1; 

    URL url = new URL(urlString); 
    URLConnection conn = url.openConnection(); 

    if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection"); 

    try{ 
     HttpURLConnection httpConn = (HttpURLConnection) conn; 
     httpConn.setAllowUserInteraction(false); 
     httpConn.setInstanceFollowRedirects(true); 
     httpConn.setRequestMethod("GET"); 
     httpConn.connect(); 

     response = httpConn.getResponseCode();     
     if (response == HttpURLConnection.HTTP_OK) { 
      in = httpConn.getInputStream();         
     } 
    } 
    catch (Exception ex) { 
     throw new IOException("Error connecting");    
    } 
    return in;  
} 

BTW:我从谷歌的搜索结果借了这两种功能。

编辑:我从线程内调用DownloadText(url)。我开始认为这可能与超时有关。可以 ?

回答

1

这将帮助你:

private static final int CONNECT_TIMEOUT_MILL = 10000; 
    private static final int READ_TIMEOUT_MILL = 3000; 
    .... 
    HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
    con.setConnectTimeout(CONNECT_TIMEOUT_MILL); 
    con.setReadTimeout(READ_TIMEOUT_MILL); 
    .... 
+0

这并不回答我的问题。我不想自己定义它,而是找出暂停的原因。 – skari

0

我以前见过类似的行为是这样的。在我的情况下,这是在AJAX调用,它也是我真正的头脑困惑者。它在我的情况下,服务器被返回的数据,而无需任何

  1. 指定内容长度或
  2. 关闭HTTP连接

于是关了浏览器必须等待连接超时在处理数据并生成接收事件之前。您的情况可能会出现类似情况,因此请打开网络分析软件并验证http正确性。我通常使用Fiddler2进行这类工作,但我不知道您是否可以使Android设备非常好地通过代理。这听起来像你控制网络服务器,所以也许可以从这个端点检查tcp数据包。