首页 > 解决方案 > HTTP post 请求在生产环境中没有响应(与 tomcat 服务器的战争)

问题描述

我已经实现了一个PerformHttpPostRequest函数,它应该发送一个包含 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块。

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

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

标签: javaapachehttptomcatwar

解决方案


嗨,Talor 很高兴认识你,请尝试使用 HttpURLConnection 来解决这个问题,如下所示:

Java - 通过 POST 方法轻松发送 HTTP 参数

祝你今天过得愉快。

教授


推荐阅读