【问题标题】:HttpClient in a loop循环中的 HttpClient
【发布时间】:2020-04-25 05:37:55
【问题描述】:

我正在使用 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 收到的响应进行了大量处理。

【问题讨论】:

    标签: java apache-commons-httpclient


    【解决方案1】:
    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);
    }
    

    你能不能试试这个。

    【讨论】:

    • 我认为每次迭代都创建一个新的PostMethod,而不是一个新的HttpClient,不是吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 2019-06-26
    • 1970-01-01
    相关资源
    最近更新 更多