網站首頁 編程語言 正文
以前寫百度貼吧搶二樓程序遇到的問題,此處做一個記錄。
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
相關推薦
- 2022-08-27 Oracle數據庫存儲過程的調試過程_oracle
- 2022-12-09 Python構造函數與析構函數超詳細分析_python
- 2022-11-21 Python?Flask實現圖片驗證碼與郵箱驗證碼流程詳細講解_python
- 2022-12-27 Python中的類的定義和對象的創建方法_python
- 2022-10-06 C語言字符串壓縮之ZSTD算法詳解_C 語言
- 2023-07-14 如何限制請求的并發數量
- 2023-03-13 Pandas數據分析常用函數的使用_python
- 2022-07-19 JDBC BLOB文件存取
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支