[英]HTTP post request doesn't respond on production environment (war with tomcat server)
我已经实现了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块,例如IOException
, Exception
和代码未到达那里。
我添加了调试打印,这些打印演示了代码在client.execute(...)
命令处停止响应。
该函数在try
块内调用,在执行.execute(...)
命令后,代码确实到达了finally
块。
我已经搜索了类似的问题,但没有找到答案。
这是一个已知问题吗? 有谁知道会导致这种情况的原因吗? 或者我该如何解决?
我已经尝试过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。 -尝试使用一种测试方法,该方法向始终可访问的服务器发出get请求。 对于google.com,请打印状态。 这样一来,您就可以知道您的代码在服务器环境中是否确实有效。 希望这可以帮助。 :)
如果代码没有超出client.execute(...)
但确实在调用代码中执行了finally
块,则可以通过将此catch块添加到包含以下内容的try
块中,找出导致中止执行的原因: finally
:
catch(Throwable x) {
x.printStackTrace();
}
Throwable
是所有异常和错误类的超类,因此捕获Throwable将捕获所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.