java - 循环中的 HttpClient
问题描述
我正在使用 Apache HttpClient 在批处理(独立)JAVA 程序中调用 API。下面是代码
HttpClient httpClient = new HttpClient();
httpClient.getParams().setIntParameter("http.connection.timeout",5000);
PostMethod postMethod = new PostMethod("http://localhost:8080/endpoint");
for (String strRequest:listA) {
postMethod.setRequestEntity(new StringRequestEntity(strRequest,"application/json","UTF-8"));
postMethod.addRequestHeader("Content-Type","application/json");
postMethod.addRequestHeader("Accept","application/json");
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode !=200) {
responseBodyStr = postMethod.getResponseBodyAsString();
} else {
responseBodyStr = postMethod.getResponseBodyAsString();
}
System.out.println(responseBodyStr);
}
在第二次迭代中,我收到 400(套接字超时)错误。有什么办法可以重置httpClient
这里,所以我可以重用同一个对象。它也将有助于我的单元测试。这是代码的简化版本。实际代码根据从 API 收到的响应进行了大量处理。
解决方案
HttpClient httpClient = null;
PostMethod postMethod = new PostMethod("http://localhost:8080/endpoint");
for (String strRequest:listA) {
httpClient = new HttpClient();
httpClient.getParams().setIntParameter("http.connection.timeout",5000);
postMethod.setRequestEntity(new StringRequestEntity(strRequest,"application/json","UTF-8"));
postMethod.addRequestHeader("Content-Type","application/json");
postMethod.addRequestHeader("Accept","application/json");
int statusCode = httpClient.executeMethod(postMethod);
if (statusCode !=200) {
responseBodyStr = postMethod.getResponseBodyAsString();
} else {
responseBodyStr = postMethod.getResponseBodyAsString();
}
System.out.println(responseBodyStr);
}
你能试试这个吗?
推荐阅读
- javascript - 导航菜单的悬停问题
- c++ - c++17 inline + thread_local vs thread_local
- php - 用数千条记录填充选择下拉列表
- cvx - CVXR:处理变量矩阵的非对角元素
- linker - Fortran 语言绑定错误:为什么不链接到 MPI 库?
- jenkins - 给定一个拉取请求 ID,我如何获取拉取请求的作者?使用 GitHub API?
- adsense - 为什么我的网站没有获得 AdSense 的批准?
- hive - HIVE:优化非分区表到分区表的连接
- javascript - 带边框的复制表格在 Firefox 中不起作用
- android - 在运行时从列表中调用函数序列