>我实现了一个PerformHttpPostRequest
函数,该函数应该发送包含JSON类型主体的post请求并通过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 文件时,请求未执行。
我尝试添加几个捕获块,例如IOException
、Exception
代码无法到达那里。
我添加了调试打印,这些打印表明代码在client.execute(...)
命令处停止响应。
该函数在try
块内调用,执行.execute(...)
命令后,代码确实会到达finally
块。
我已经搜索了类似的问题,但没有找到答案。
这是一个已知问题吗?有谁知道是什么会导致这种情况?或者我该如何解决它?
嗨,塔洛很高兴认识你, 请尝试使用 HttpURLConnection 来解决此问题,如下所示:
Java - 通过 POST 方法轻松发送 HTTP 参数
有好的一天。
埃尔·普罗菲索尔
我已经尝试过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);
它非常简单无忧,希望对您有所帮助
您可以尝试的几件事。 - 尝试从您正在运行雄猫的那个框中执行 ping/curl。 - 尝试使用一种测试方法,该方法向始终可访问的服务器发出 get 请求。对于 ex google.com 并打印状态。这样,您就可以知道您的代码在服务器环境中是否实际工作。 希望这有帮助。:)
如果代码没有超出client.execute(...)
,但它确实在调用代码中执行了finally
块,那么您可以通过将此 catch 块添加到包含finally
的try
块来找出导致执行中止的原因:
catch(Throwable x) {
x.printStackTrace();
}
Throwable
是所有异常和错误类的超类,因此捕获 Throwable 将捕获所有内容。