401 nobody
请求体编码需要要对应的消息体转换器
private List<HttpMessageConverter<?>> getConverts() {
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
StringHttpMessageConverter stringConvert = new StringHttpMessageConverter();
List<MediaType> stringMediaTypes = new ArrayList<MediaType>() {{
add(MediaType.TEXT_PLAIN);
add(MediaType.TEXT_HTML);
add(MediaType.APPLICATION_JSON);
}};
stringConvert.setSupportedMediaTypes(stringMediaTypes);
messageConverters.add(stringConvert);
return messageConverters;
}
表单请求
restTemplate 的表单请求必须使用MultiValueMap提交参数
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("key","value");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
JSON 请求
请求会把请求体转成 json格式,安装需要的json格式定义实体即可。
Map<String, Object> map = new HashMap<>();
map.put("username", LOGIN_USER_NAME);
map.put("password", LOGIN_PWD);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Map<String, Object>> param = new HttpEntity<>(map, headers);
ParameterizedTypeReference<IotR<ObjectNode>> typeRef =
new ParameterizedTypeReference<IotR<ObjectNode>>() {
};
IotR<ObjectNode> responseData = restTemplate.exchange(LOGIN_URL, HttpMethod.POST, param, typeRef).getBody();
url参数请求
参数需要在url中使用占位符,把参数封装在Map中传递给Map<String, ?> uriVariables 编码,不然会有奇怪的问题出现。
HashMap<String,Object> map = new HashMap<>();
map.put("customName",customName);
map.put("everyDay",everyDay);
ParameterizedTypeReference<AirR<AirBatchData>> typeRef = new ParameterizedTypeReference<AirR<AirBatchData>>() {};
String url = AIR_DATA_BATCH_URL
+ "?customName={customName}"
+ "&everyDay={everyDay}";
ResponseEntity<AirR<AirBatchData>> forEntity = restTemplate.exchange(url, HttpMethod.GET, null, typeRef,map);
|