Http Post和网络延迟

时间:2012-05-08 11:17:55

标签: java android http

我需要在应用程序启动时对不同的Web服务(php)进行大约15次调用。

我使用以下代码发布帖子

public static String post(String url, List<BasicNameValuePair> 
           postvalues, HttpClient httpclient) {
    try {
        if (httpclient == null) {
            httpclient = new DefaultHttpClient();
        }
        HttpPost httppost = new HttpPost(url);

        if ((postvalues == null)) {
            postvalues = new ArrayList<BasicNameValuePair>();
        }
        httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        return requestToString(response);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

}



private static String requestToString(HttpResponse response) {
    String result = "";
    try {
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line + "\n");
        }
        in.close();
        result = str.toString();
    } catch (Exception ex) {
        result = "Error";
    }
    return result;
}

问题在于,必须按照给定的顺序请求某些请求,并且每个请求大约需要1-2秒,因此#34;加载启动&#34;大约需要10秒钟。

所以我的问题是:由于所有连接都是同一台服务器,我该如何改善这种延迟呢?有没有办法打开一个连接,并通过那个&#34;隧道&#34;发送所有的请愿减少延迟?

注意:我测试了代码,请求在同一时间重新使用httpclient在每个连接中使用新的

由于

1 个答案:

答案 0 :(得分:2)

您的想法是HTTP持久连接,它重用TCP连接。

关于这个话题已经有了一个很好的问题&amp;在Stackoverflow上回答:

Persistent HttpURLConnections on Android

相关问题