restTemplate.postForObject

简介: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";
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值