RestTemplate请求第三方接口的时候,请求失败或者没有成功,没有抛异常出来,自己在catch中打印的日志也看不到。下面直接看代码吧,直接拿去可以用的。抛异常的时候可以换一种异常试试,比如RestClientResponseException、HttpClientErrorException。下面的那个方法是借用他人的
public void getTest() {
JSonObject json = new JSonObject();
json.put("msg", "1234567");
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
//初始化请求头
HttpHeaders headers = new HttpHeaders() {
{
add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
add(HttpHeaders.HOST, "cmccdevops-test-pod6-devops.hu6-173-77.4a.cmit.cloud");
}
};
try {
//请求第三方接口
String result = restTemplate.postForEntity(
URI.create(httpConstant.getCallBackCaseAddress()),
new HttpEntity<>(json.toString(), headers),
String.class).getBody();
log.info("请求成功返回结果:{}", result);
} catch (Exception e) {
log.info("请求失败返回结果:{}",getStackTrace(e));
}
public static String getStackTrace(Exception e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
e.printStackTrace(pw);
pw.flush();
sw.flush();
} finally {
if (sw != null) {
try {
sw.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (pw != null) {
pw.close();
}
}
return sw.toString();
}