我正在调用 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);
}
}
}
那么好还是不好?