2013-01-18 84 views
2

对于我的应用程序,我需要从本地网络上的服务器上托管的网页获取最新数据。Android:快速Web请求

因此,我要求最新的页面与HTTP GET,当收到数据时,我发送另一个请求。

在我目前的实现中,每个请求的响应时间为100 - 120毫秒。有没有可能使这更快,因为它是相同的网址,请求。

例如,保持连接在页面上打开并在不设置新连接的情况下刷新最新数据?

此页面大约900-1100字节。

HTTP GET代码:

public static String makeHttpGetRequest(String stringUrl) { 

    try { 
     URL url = new URL(stringUrl); 
     HttpURLConnection con = (HttpURLConnection) url.openConnection(); 
     con.setReadTimeout(300); 
     con.setConnectTimeout(300); 
     con.setDoOutput(false); 
     con.setDoInput(true); 
     con.setChunkedStreamingMode(0); 
     con.setRequestMethod("GET"); 

     return readStream(con.getInputStream()); 
    } catch (IOException e) { 
     Log.e(TAG, "IOException when setting up connection: " + e.getMessage()); 
    } 
    return null; 
} 

阅读的InputStream

private static String readStream(InputStream in) { 
    BufferedReader reader = null; 
    StringBuilder total = new StringBuilder(); 
    try { 
     String line = ""; 
     reader = new BufferedReader(new InputStreamReader(in)); 
     while ((line = reader.readLine()) != null) { 
      total.append(line); 
     } 
    } catch (IOException e) { 
     Log.e(TAG, "IOException when reading InputStream: " + e.getMessage()); 
    } finally { 
     if (reader != null) { 
      try { 
       reader.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return total.toString(); 
} 

回答

0

据我知道有没有像你所要求的实现。我一直在处理很多http请求,你能做的最好的事情就是你的代码。还有一件事需要注意......你的连接速度可能很慢,取决于连接时间可能更多,或者在某些情况下,我一直在处理很多连接的超时时间不够大,但这是服务器问题。

在我看来,你应该使用你现在拥有的东西。