我正在为我定期轮询并根据特定响应向其发送消息的服务器设置 Java 客户端。我在课堂上使用的策略如下:
public class PollingClient {
private HttpClient client = getHttpClient(); // I get a DefaultHttpClient this way so it's easier to add connection manager and strategy etc to the client later
private HttpPost httpPost = getHttpPost(); // same idea, I set headers there
public String poll () {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("id", someId));
String responseString = null;
try {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setURI(polluri));
httppost.setEntity(formEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
responseString = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
public void send(String msg) {
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("msg", msg));
formparams.add(new BasicNameValuePair("id", someId));
String responseString = null;
try {
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setURI(new URI(URL + "send"));
httppost.setEntity(formEntity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
responseString = EntityUtils.toString(entity);
}
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
}
}
}
我启动一个线程,在 3 秒左右进行轮询。我可以根据轮询结果从主线程发送消息。该代码有效,但一直给我以下两个例外,但在两者之间继续工作。
java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
org.apache.http.NoHttpResponseException: The target server failed to respond.
我可以忽略异常,但我想知道发生了什么。我无法通过 Google 找到任何解决方案。我尝试过使用内容,HttpPost
在 send 方法中创建一个新对象,诸如此类的东西,但到目前为止没有任何帮助。
对于这种情况有什么好的策略。我目前keep-alive
在对象中设置标题HttpPost
以防万一。除此之外,我不认为有什么我做的。我认为这与整体战略有关。我不想为每个连接创建新对象,但我也不知道推荐的重用级别。谢谢你的帮助。哦.. 这是 HttpClient 4.2.2