JAVA中处于循环中的HttpClient

问题描述 投票:1回答:1

[我正在使用Apache HttpClient调用批处理(STANDALONE)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 api httpclient
1个回答
0
投票
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);
}

您能尝试一下吗。

© www.soinside.com 2019 - 2024. All rights reserved.