2012-05-08 108 views
1

我需要在应用程序启动时对不同的Web服务(php)进行约15次调用。Http Post和网络延迟

我用下面的代码后

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秒钟,这样的“加载飞溅“大约需要10秒。

所以我的问题是:由于所有的连接都是在同一台服务器上,我该如何改善这种延迟?有什么方法可以打开连接,并通过该“隧道”发送所有请愿以减少延迟?

注:我测试的代码和请求采取相同的时间用在每个连接一个新的

感谢

+0

如果你不能并行的呼叫,然后你需要找到瓶颈所在,并删除它们。我们不能告诉你他们在哪里;你必须测量。它是网络I/O吗? PHP Web服务本身很慢吗?为什么不能使用不需要太多个人电话的“更好”的Web服务? –

+0

您是否也控制服务器实施?然后,您可以在一个(或几个)请求下合并这些服务。此外,服务或网络延迟的答复时间是否为1-2秒? – jhonkola

+1

我建议你用'EntityUtils.toString(response.getEntity())'替换你的'requestToString()'方法 - 它的代码更少,错误处理更好,并且服从服务器发送的字符编码。 –

回答