我正在调用REST URL,并尝试测量获取响应所需的时间。
我正在使用DefaultHttpClient
从REST URL
获取响应。
在我的以下程序中,每个线程将在特定范围内工作。例如:每个线程将在1-100
之间工作,第二个线程将在101-200
之间工作,等等。
因此,在我的以下代码中,第一次正常工作。但是第二次,在这一行httpclient.execute
处会抛出异常-
java.lang.IllegalStateException: Invalid use of BasicClientConnManager: connection still allocated.
Make sure to release the connection before allocating another one.
我在这里做错了什么吗?-
以下是我的代码-
class Task implements Runnable {
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet httpGet;
private HttpResponse response;
@Override
public void run() {
try {
httpGet = new HttpGet(
"http://localhost:8080/service/BEService/v1/get/USERID=10000/profile.ACCOUNT.SERVICE
httpGet.getRequestLine();
for (int userId = id; userId < id + noOfTasks; userId++) {
long start = System.nanoTime();
response = httpclient.execute(httpGet);
long end = System.nanoTime() - start;
}
} catch (Exception e) {
LOG.error("Threw a Exception in " + getClass().getSimpleName(), e);
}
}
}
更新的代码:
如果我像这样做-
class Task implements Runnable {
private DefaultHttpClient httpclient = new DefaultHttpClient();
private HttpGet httpGet;
private HttpResponse response;
@Override
public void run() {
try {
for (int userId = id; userId < id + noOfTasks; userId++) {
httpGet = new HttpGet("http://localhost:8080/service/BEService/v1/get/USERID=10000/profile.ACCOUNT.SERVICE");
httpGet.getRequestLine();
long start = System.nanoTime();
response = httpclient.execute(httpGet);
long end = System.nanoTime() - start;
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
}
} catch (Exception e) {
LOG.error("Threw a Exception in " + getClass().getSimpleName(), e);
}
}
}
那么这样可以吗?