Java HTTP post请求不';无法在生产环境中响应(与tomcat服务器的战争)

Java HTTP post请求不';无法在生产环境中响应(与tomcat服务器的战争),java,apache,http,tomcat,war,Java,Apache,Http,Tomcat,War,我已经实现了一个performhtppostrequest函数,该函数应该发送一个包含JSON类型主体的post请求,并通过ApacheHttpClient获得JSON响应 public static String PerformHttpPostRequest(String url, String requestBody) throws IOException { CloseableHttpClient client = HttpClients.createDefault(); HttpPos

我已经实现了一个
performhtppostrequest
函数,该函数应该发送一个包含JSON类型主体的post请求,并通过ApacheHttpClient获得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块,比如
IOException
Exception
,但代码没有到达那里

我添加了调试打印,它演示了代码在
client.execute(…)
命令处停止响应

函数在
try
块内调用,执行
.execute(…)
命令后,代码最终到达

我已经搜索了一个类似的问题,但没有找到答案

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

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

祝你今天愉快


el profesor

我试过使用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);
RequestObject RequestObject=newrequestobject();
setKey(“abcd”);
setEndpoint(serviceEndPoint);
RestTemplate RestTemplate=新RestTemplate();
HttpEntity requestBody=新的HttpEntity(
请求对象);
ResponseEntity结果=restTemplate.postForEntity(
serviceEndPoint、requestBody、RequestObject.class);

它非常简单,没有麻烦,希望它能帮助你尝试一些东西。 -试着从运行tomcat的那个盒子中执行ping/curl。 -尝试使用一种测试方法,向始终可访问的服务器发出get请求。用于ex google.com并打印状态。这样,您就可以知道您的代码是否在ServerEnv中实际工作。
希望这有帮助。:)

如果代码没有超出
client.execute(…)
的范围,但它确实执行调用代码中的
finally
块,那么您可以通过将此catch块添加到包含
finally
try
块中,找出导致中止执行的原因:

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

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

您可以检查ping ip,或者尝试从rest客户端(如postman)访问服务吗。乍一看,似乎有防火墙堵塞。使用了哪些库和框架?@Saurabhjhunjhunla我已经使用了postman,服务器可用且工作正常。@SajithNeyomal我使用的是org.apache.http.impl.client.HttpClients liabries。这不应该是公认的答案。ApacheHttpClient实际上可以工作,因此解决方案不仅仅是“使用另一个库”。当然,这个问题甚至没有描述问题是什么,所以解决方法也很简单,就是“你试过重新启动电脑吗?”