Android中的多个Http连接

时间:2011-06-13 16:35:48

标签: android http connection

我有一个线程,用于访问Web服务器并在数据可用时检索一些数据。这是COMET实现,因此在数据可用之前服务器不会返回响应。这是代码:

HttpParams httpParameters = new BasicHttpParams();
httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 100);
httpParameters.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, 100);

int timeoutConnection = 120000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);

int timeoutSocket = 7200000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

HttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpPost httpPost = new HttpPost("http://www.someurl.com/PageA");
HttpResponse  response = httpClient.execute(httpPost);

现在,第二个线程用于访问同一服务器以执行其他任务。这是代码:

URL url = new URL("http://www.someurl.com/PageB");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.connect();

// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();

String line = null;
while ((line = reader.readLine()) != null)
{
  stringBuilder.append(line + "\n");
}

String response = stringBuilder.toString();

问题是当第一个线程被阻塞等待响应时,第二个线程无法到达服务器。它只会挂起,直到第一个线程收到响应。

我的印象是,应该可以有多个独立的连接,这些连接彼此独立运行。或者我误解了这是如何工作的?有关如何使多个单独的连接工作的任何建议?谢谢!

0 个答案:

没有答案