在Java中,我希望每隔5秒发送一次HttpPost,而不等待响应。我该怎么做呢?
我使用以下代码:
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
StringEntity params = new StringEntity(json.toString() + "\n");
post.addHeader("content-type", "application/json");
post.setEntity(params);
httpClient.execute(post);
Thread.sleep(5000);
httpClient.execute(post);但它不起作用。
即使我失去了前一个连接,并建立了一个新的连接来发送第二个连接,第二个execute函数总是被阻塞。
发布于 2013-07-05 08:57:59
你的问题留下了一堆问题,但它的基本点可以通过以下方式实现:
while(true){ //process executes infinitely. Replace with your own condition
Thread.sleep(5000); // wait five seconds
httpClient.execute(post); //execute your request
}发布于 2013-07-05 09:57:11
我尝试了你的代码,我得到了一个异常: java.lang.IllegalStateException:无效使用BasicClientConnManager:仍然分配的连接。确保在分配另一个连接之前释放该连接。
此异常已记录在HttpClient 4.0.1 - how to release connection?中
我可以通过使用以下代码的响应来释放连接:
public void sendMultipleRequests() throws ClientProtocolException, IOException, InterruptedException {
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://www.google.com");
HttpResponse response = httpClient.execute(post);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
Thread.sleep(5000);
response = httpClient.execute(post);
entity = response.getEntity();
EntityUtils.consume(entity);
}发布于 2013-07-05 15:37:47
使用DefaultHttpClient是同步的,这意味着程序会被阻塞,等待响应。相反,您可以使用Maven库来执行异步请求(如果您不熟悉async-http-client,可以从search.maven.org下载jar文件)。示例代码可能如下所示:
import com.ning.http.client.*; //imports
try {
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
while(true) {
asyncHttpClient
.preparePost("http://your.url/")
.addParameter("postVariableName", "postVariableValue")
.execute(); // just execute request and ignore response
System.out.println("Request sent");
Thread.sleep(5000);
}
} catch (Exception e) {
System.out.println("oops..." + e);
}https://stackoverflow.com/questions/17479705
复制相似问题