for循环中调用CloseableHttpClient代码未执行完毕就自动停止

问题背景:我在一个for循环中需要每次循环时调用高德地图的api进行计算2点之间的距离。有300条数据,试了很多次大概在80多条或100多条时,for循环就自动停止了不继续循环了。

以下是刚开始有BUG的http工具类中的get请求方法的代码:

复制代码
    /**
     * 带参数的get请求
     *
     * @param url
     * @param param
     * @return String
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.info("带参doGet请求异常:"+response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }

有log.info日志,我知道了for循环不继续执行的原因,是因为循环的某次请求调用高德地图API发生了401错误,而这个http请求一直不关闭,导致for循环就一直卡在这里不继续执行。虽然我这个http工具类的doGet()方法为了防止http请求失败,而做了return处理。但是经测试发现一旦http请求异常,返回代码不是200时,并不会直接return跳出doGet()方法。

出现这个问题的原因:http请求失败时,请求连接并没有及时释放

解决办法:无论http请求成功还是失败,都应该在请求完成后及时释放连接资源。即添加如下代码

复制代码
httpGet.releaseConnection();

那么修改后的代码为:

复制代码
/**
     * 带参数的get请求
     *
     * @param url
     * @param param
     * @return String
     */
    public static String doGet(String url, Map<String, String> param) {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();

        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            // 创建uri
            URIBuilder builder = new URIBuilder(url);
            if (param != null) {
                for (String key : param.keySet()) {
                    builder.addParameter(key, param.get(key));
                }
            }
            URI uri = builder.build();
            // 创建http GET请求
            HttpGet httpGet = new HttpGet(uri);
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
            } else {
                log.info("带参doGet请求异常:"+response.getStatusLine().getStatusCode());
            }
            //释放链接资源,不然频繁调用该接口时,如果某次调用失败会卡住,影响下次调用
            httpGet.releaseConnection();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
相关推荐
SimonKing1 小时前
Typora 收费,开源产品Textus或可替代,还支持AI
java·后端·程序员
泡海椒1 小时前
Java 生成资金流向图 PDF:jquick-pdf 树图(JTreeChartData)节点尺寸与间距的追问记录
java·python·pdf
Rain的Java大神之路1 小时前
别再死背八股了:读完 Spring 7.0.8 源码,我学会了"改"框架
java·后端·面试
旖旎夜光1 小时前
【C 语言】(二)模拟实现 strlen、strcpy、strcmp、strstr、memcpy、memmove
c语言·开发语言·笔记·学习
codeejun2 小时前
每日一Go·MySQL-22、幻读、不可重复读、脏读实战演示
开发语言·mysql·golang
云草桑3 小时前
C#入坑JAVA 潜规则 API Get 多参数 Spring Boot与Spring Cloud 区别 入门系列4
java·开发语言
码途行者11 小时前
每天10分钟学Go:第17课 接口interface-只规定“能做什么“,不管它是什么
开发语言·后端·golang
头发还在的女程序员11 小时前
Java充电桩平台源码解析:枪口状态、上报时间与页面刷新怎样协同
java·开发语言·充电桩系统·充电桩管理·充电系统·充电小程序
timeDifference₇12 小时前
Python Vibe Coding实操实验报告
开发语言·jvm·python
geovindu13 小时前
python:DecisionTree
开发语言·后端·python·算法