大家好,又见面了,我是你们的朋友全栈君。
背景:
跨模块通过post请求调用指定接口,返回415
415状态码解释:
Unsupported Media Type
对于当前请求的方法和所请求的资源,请求中提交的实体并不是服务器中所支持的格式,因此请求被拒绝
错误日志:
org.springframework.web.client.HttpClientErrorException: 415 null
atorg.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:86)
at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:708)
功能错误代码和正常代码比对
异常请求返回415:
RestTemplate restTemplate = new RestTemplate();
String url = "http://172.16.17.82/portal/zcm-cmdb/remote/exec";
String cmd = "mkdir -p /tmp/lushuan/test5";
// 1、异常请求返回 415
HttpHeaders headers = new HttpHeaders();
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("host", "172.16.24.220");
map.add("user", "root");
map.add("cmd", cmd);
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
Object data = restTemplate.postForObject(url,request,Object.class);
LOGGER.info("TestRestTemplate testInstallCollectdByRemote data = {}", data);
正常代码演示1:
RestTemplate restTemplate = new RestTemplate();
String url = "http://172.16.17.82/portal/zcm-cmdb/remote/exec";
String cmd = "mkdir -p /tmp/lushuan/test6";
Map<String, String> map = new HashMap<>();
map.put("host","172.16.24.220");
map.put("user","root");
map.put("cmd",cmd);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, String>> request = new HttpEntity<>(map, headers);
JSONObject data = restTemplate.postForObject(url,request, JSONObject.class);
LOGGER.info("TestRestTemplate testInstallCollectdByRemote data = {}", data);
正常代码演示2:
RestTemplate restTemplate = new RestTemplate();
String url = "http://172.16.17.82/portal/zcm-cmdb/remote/exec";
String cmd = "mkdir -p /tmp/lushuan/test7";
Map<String, String> map = new HashMap<>();
map.put("host","172.16.24.220");
map.put("user","root");
map.put("cmd",cmd);
// ParameterizedTypeReference 该类的目的是启用捕获和传递泛型
ParameterizedTypeReference<String> typeRef = new ParameterizedTypeReference<String>() {
};
JSONObject createDbJsonObject = JSONObject.fromObject(map);
HttpEntity<JSONObject> entityPost = new HttpEntity<JSONObject>(createDbJsonObject);
ResponseEntity<String> createDbResponse = restTemplate.exchange(url, HttpMethod.POST, entityPost,typeRef);
HttpStatus statusCode = createDbResponse.getStatusCode();
LOGGER.info("TestRestTemplate testInstallCollectdByRemote createDbResponse = {}", createDbResponse);
LOGGER.info("TestRestTemplate testInstallCollectdByRemote statusCode = {}", statusCode);
两段代码的实现方式都可以,推荐第二种,可以获取返回的状态码,是否跨域等信息。
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/146140.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...