开发者

Multiple Http connections in Android

开发者 https://www.devze.com 2023-03-12 08:12 出处:网络
I have a thread that is used to access a web server and retrieve some data when the data is available. This is a COMET implementation, so the server doesn\'t return the response until data is availabl

I have a thread that is used to access a web server and retrieve some data when the data is available. This is a COMET implementation, so the server doesn't return the response until data is available. Here is the code:

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);

Now a second thread is used to access the same server to perform some other task. Here is the code for that:

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();

The problem is that when the first thread is 开发者_StackOverflow中文版blocked waiting for a response, the second thread isn't able to reach the server. It just hangs until the first thread has received its response.

I was under the impression that it should be possible to have multiple separate connections that operate independent of each other. Or have I misunderstood how this works? Any suggestions on how to get multiple separate connections to work? Thank you!

0

精彩评论

暂无评论...
验证码 换一张
取 消