如何使用RestTemplate设置请求参数
RestTemplate设置请求参数的方式根据请求类型(GET/POST)和参数形式(路径参数、查询参数、JSON请求体)有所不同,以下是具体实现方法:
一、GET请求参数设置
-
路径参数
使用占位符{param}
,通过Map
或可变参数传递:// 使用Map传参 Map<String, String> uriVariables = new HashMap<>(); uriVariables.put("id", "123"); String result = restTemplate.getForObject("http://example.com/api/{id}", String.class, uriVariables); // 或使用可变参数 String result = restTemplate.getForObject("http://example.com/api/{id}", String.class, "123");
-
查询参数
使用UriComponentsBuilder
构建带参数的URL:UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://example.com/api/data") .queryParam("name", "John") .queryParam("age", 25); String url = builder.toUriString(); String result = restTemplate.getForObject(url, String.class);
二、POST请求参数设置
-
JSON请求体
使用HttpEntity
封装嵌套JSON参数,并设置请求头:// 构建嵌套参数 Map<String, Object> paramMap = new HashMap<>(); Map<String, String> queryMap = new HashMap<>(); queryMap.put("c1", "value1"); paramMap.put("a", "valueA"); paramMap.put("b", queryMap); // 设置请求头 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<Map<String, Object>> entity = new HttpEntity<>(paramMap, headers); // 发送请求 String response = restTemplate.postForObject("http://example.com/api", entity, String.class);
引用示例中的多层嵌套JSON构建方式。
-
表单参数
使用MultiValueMap
传递表单数据:HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add("username", "admin"); formData.add("password", "123456"); HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(formData, headers); ResponseEntity<String> response = restTemplate.postForEntity("http://example.com/login", entity, String.class);
三、配置RestTemplate超时(可选)
通过配置类设置连接和读取超时:
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(10000); // 10秒
factory.setReadTimeout(10000); // 10秒
return new RestTemplate(factory);
}
}
引用配置类示例。
四、处理复杂响应
解析JSON响应并提取数据:
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
JSONObject jsonResponse = new JSONObject(response.getBody());
if ("0000".equals(jsonResponse.getJSONObject("parameter").getString("code"))) {
String result = jsonResponse.getString("result");
}
引用响应处理方法。
相关问题