gpt4 book ai didi

java - 循环中的 HttpClient

转载 作者:太空宇宙 更新时间:2023-11-04 09:11:23 25 4
gpt4 key购买 nike

我正在使用 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);
}

你能试试这个吗?

关于java - 循环中的 HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59633072/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com