在对SonarQube中的以下代码进行代码分析时,我发现我建议关闭HttpClient。
import org.apache.http.impl.client.CloseableHttpClient;
public void request() {
CloseableHttpClient httpclient = null;
try {
httpclient = HttpClients.createDefault();
/**
* Rest of the code
*/
} catch(IOException e) {
LOGGER.error("Error in processing : {}", e.getMessage(), e);
} finally {
try {
if(httpclient != null) {
httpclient.close();
}
} catch(IOException e) {
LOGGER.error("Error in closing client : {}", e.getMessage(), e);
}
}
}
SonarQube仍然抱怨httpclient
应该关闭,即使我在finally
区块关闭它。
SonarQube给出的错误:
Close this "CloseableHttpClient".
Java - 1.8 SonarQube - 5.6
任何想法我可能做错了什么。感谢
答案 0 :(得分:0)
使用资源试用
public void request() {
try (CloseableHttpClient httpclient = HttpClients.createDefault()){
/**
* Rest of the code
*/
} catch(IOException e) {
LOGGER.error("Error in processing : {}", e.getMessage(), e);
}
}