日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

關于httpclient中多次執行execute阻塞問題,卡住不動了解決方式。

作者:_NeverSayNo 更新時間: 2022-01-27 編程語言

以前寫百度貼吧搶二樓程序遇到的問題,此處做一個記錄。

httpclient多次進行post請求的時候,會阻塞,無法循環執行(不知道現在的版本還會不會)。網上查過解決方法,在循環體內每次new一個httpclient可以解決,但是感覺不是常規解決方案,最終通過以下方式解決。

問題偽代碼如下:

public static void main(String[] args) {
        HttpClient httpClient = new HttpClient();
        while (true){
            HttpGet get = new HttpGet("http://test.com");
            HttpResponse responseGet = httpClient.execute(get);
            String[] responseStr = EntityUtils.toString(response.getEntity());
            for(i=0;i<responseStr.size();i++){
                String tempStr = responseStr[i];
                HttpPost post = new HttpPost("http://test.com");
                Map<String, String> paramMap = new HashMap<String, String>();
                paramMap.put("id","123");
                paramMap.put("name", postName);
                post.setParam(paramMap);
                HttpResponse responsePost = httpClient.execute(post);//第一次循環可以執行到這一句,下一次就一直卡死在此處.
                //do something
            }
        }
    }
    //只能循環post提交一次,第二次就卡在注釋處不動,也不報錯

解決方式很簡單,其實是因為response結果集未關閉,在做完數據結果處理后關閉結果集即可。修正后代碼如下:

public static void main(String[] args) {
        HttpClient httpClient = new HttpClient();
        while (true){
            HttpGet get = new HttpGet("http://test.com");
            HttpResponse responseGet = httpClient.execute(get);
            String[] responseStr = EntityUtils.toString(response.getEntity());
            for(i=0;i<responseStr.size();i++){
                String tempStr = responseStr[i];
                HttpPost post = new HttpPost("http://test.com");
                Map<String, String> paramMap = new HashMap<String, String>();
                paramMap.put("id","123");
                paramMap.put("name", postName);
                post.setParam(paramMap);
                HttpResponse responsePost = httpClient.execute(post);//第一次循環可以執行到這一句,下一次就一直卡死在此處.
                //do something
                responsePost.getEntity().getContent().close();//關閉結果集
            }
        }
    }

?

原文鏈接:https://blog.csdn.net/li939403600/article/details/89050031

欄目分類
最近更新