HTTP post 请求在生产环境中没有响应(war 使用 tomcat 服务器)

HTTP post request doesn't respond on production environment (war with tomcat server)

我已经实现了一个 PerformHttpPostRequest 函数,它应该发送一个 post 请求包含一个 JSON 类型的主体,并通过 Apache HttpClient 获得一个 JSON 响应。

public static String PerformHttpPostRequest(String url, String requestBody) throws IOException {

CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);

StringEntity entity = new StringEntity(requestBody);

httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

CloseableHttpResponse response = client.execute(httpPost);

HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();

return (new BufferedReader(new InputStreamReader(is, "UTF-8"))).readLine();
}

问题是,代码在开发环境中运行完美,但是当 运行 带有 tomcat 服务器的 war 文件时,请求没有被执行。

我已经尝试添加几个 catch 块,例如 IOExceptionException,但代码没有到达那里。

我添加了调试打印,证明代码在 client.execute(...) 命令中停止响应。

该函数在 try 块内调用,执行 .execute(...) 命令后,代码确实到达 finally 块。

我已经搜索过类似的问题,但没有找到答案。

这是一个已知问题吗?有谁知道是什么原因造成的?或者我该如何解决?

嗨,塔洛尔,很高兴认识你, 请尝试使用 HttpURLConnection 解决此问题,如下所示:

祝你有愉快的一天。

教授

我试过使用 RestTemplate。

RequestObject requestObject = new RequestObject();
        requestObject.setKey("abcd");
        requestObject.setEndpoint(serviceEndPoint);

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<RequestObject> requestBody = new HttpEntity<RequestObject>(
                requestObject);

        ResponseEntity<RequestObject> result = restTemplate.postForEntity(
                serviceEndPoint, requestBody, RequestObject.class);

它非常简单且无忧无虑,希望对您有所帮助

您可以尝试的东西很少。 - 尝试从你所在的方框 运行 tomcat 开始 ping/curl。 - 尝试使用一种测试方法,向始终可访问的服务器发出获取请求。对于 ex google.com 并打印状态。这样您就可以知道您的代码在服务器环境中是否实际工作。 希望这可以帮助。 :)

如果代码没有超出 client.execute(...) 但确实执行了调用代码中的 finally 块,那么您可以通过将此 catch 块添加到包含 finally:

try
catch(Throwable x) {
    x.printStackTrace();
}

Throwable 是所有异常和错误的超类 类,因此捕获 Throwable 将捕获所有内容。