首页 > 解决方案 > 循环中的 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 收到的响应进行了大量处理。

标签: javaapache-commons-httpclient

解决方案


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);
}

你能试试这个吗?


推荐阅读