简介:RestTemplate是Spring提供的HTTP请求调用工具
导入包:org.springframework.web.client.RestTemplate
三种postForObject方法
postForObject(URI url, Object request, Class responseType): T - RestTemplate
postForObject(String url, Object request, Class responseType, Map< String,?> uriVariables): T - RestTemplate
postForObject(String url, Object request, Class responseType, Object… uriVariables): T - RestTemplate
参数含义
String url 请求的URL路径
Object request 请求的body,通过@RequestBody接收传过去的值
Class responseType 请求完成之后返回的结果类型
Map< String,?> uriVariables POST请求中要传过去的参数
Object… uriVariables 可以放零个或多个Object类型的参数
使用
使用Map传值
import org.springframework.web.client.RestTemplate
@Service
public class DemoServiceImpl implements DemoService {
@Override
public void send(){
Map<String, String> input = new HashMap<String, String>();
RestTemplate restTemplate = new RestTemplate();
String url = "http://xxx/api/send.do"
input.put("username", "admin");
input.put("mobile", "13312340066");
String sendResultStr = restTemplate.postForObject(url+"?username={username}&mobile={mobile}", null, String.class, input);
}
}
使用可变长参数传值
import org.springframework.web.client.RestTemplate
@Service
public class DemoServiceImpl implements DemoService {
@Override
public void send(){
Map<String, String> input = new HashMap<String, String>();
RestTemplate restTemplate = new RestTemplate();
String url = "http://xxx/api/send.do"
String username = "admin";
String mobile = "13312340066";
String sendResultStr = restTemplate.postForObject(url+"?username={username}&mobile={mobile}", null, String.class, username, mobile);
}
}
使用request传值
import org.springframework.web.client.RestTemplate
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
@Service
public class DemoServiceImpl implements DemoService {
@Override
public void send(){
Map<String, String> input = new HashMap<String, String>();
RestTemplate restTemplate = new RestTemplate();
String url = "http://xxx/api/send.do"
MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<>();
paramMap.add("username", "admin");
paramMap.add("mobile", "13312340066");
String sendResultStr = restTemplate.postForObject(url, paramMap, String.class);
}
}
接收值
@Controller
public class DemoController {
@PostMapping("/api/send.do")
public String home(String username, String mobile){
return "success";
}
}