我使用apache HTTP客户端API在Java中编写了我的客户端程序。我想要做的是向服务器发送请求。如果发送的请求的响应代码不是200,那么我必须向服务器重新发送请求。这样做时我收到以下错误。
java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
at org.apache.http.impl.conn.BasicClientConnectionManager.getConnection(BasicClientConnectionManager.java:162)
at org.apache.http.impl.conn.BasicClientConnectionManager$1.getConnection(BasicClientConnectionManager.java:139)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:456)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at main.ApacheGet.sendGet(ApacheGet.java:31)
at main.ApacheGet.main(ApacheGet.java:17)
我正在努力实现LongPolling。当我收到回复时,我发送了一个新请求。如果我收到200以外的响应代码,我会发送一个新请求。我明白这个错误意味着什么,但我不知道如何克服它。以下是我的代码。
private void sendGet() throws Exception {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(
"http://localhost:8080/MyServlet/Servlet?id=1001");
System.out.println("Started");
HttpResponse response;
while (true) {
System.out.print("looped back");
response = client.execute(request);
int status = response.getStatusLine().getStatusCode();
System.out.println("Got the response. Status code:" + status);
if (status == 200) {
StringBuffer textview = new StringBuffer();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
textview.append(line);
}
System.out.print(textview.toString());
}
else{
continue;
}
}
}
提前致谢:)。