请求体编码需要要对应的消息体转换器
private List表单请求> getConverts() { List > messageConverters = new ArrayList<>(); // String转换器 StringHttpMessageConverter stringConvert = new StringHttpMessageConverter(); List stringMediaTypes = new ArrayList () {{ //添加响应数据格式,不匹配会报401 add(MediaType.TEXT_PLAIN); add(MediaType.TEXT_HTML); add(MediaType.APPLICATION_JSON); }}; stringConvert.setSupportedMediaTypes(stringMediaTypes); messageConverters.add(stringConvert); return messageConverters; }
restTemplate 的表单请求必须使用MultiValueMap提交参数
MultiValueMapJSON 请求map = new linkedMultiValueMap<>(); map.add("key","value"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); HttpEntity > param = new HttpEntity<>(map, headers);
请求会把请求体转成 json格式,安装需要的json格式定义实体即可。
//请求参数
Map map = new HashMap<>();
map.put("username", LOGIN_USER_NAME);
map.put("password", LOGIN_PWD);
//请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//构造请求体
HttpEntity
url参数请求
参数需要在url中使用占位符,把参数封装在Map中传递给Map
//构造请求
HashMap map = new HashMap<>();
map.put("customName",customName);
map.put("everyDay",everyDay);
ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() {};
String url = AIR_DATA_BATCH_URL
+ "?customName={customName}"
+ "&everyDay={everyDay}";
ResponseEntity> forEntity = restTemplate.exchange(url, HttpMethod.GET, null, typeRef,map);



