RestTemplate中的三种请求方式postForObject、postForEntity、exchange

启动类配置参数

@SpringBootApplication
@EnableDiscoveryClient
public class HelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }

    @Bean
    @LoadBalanced
    RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

测试类

	public static void main(String[] args) {
		RestTemplate template = new RestTemplate();
    	String url = "http://127.0.0.1:12813/member/c2/f02";
    	// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
    	MultiValueMap<String, Object> paramMap = new LinkedMultiValueMap<String, Object>();
    	paramMap.add("dt", "{\"uscInfo\":{\"member\":\"123\",\"isEncrypt\":0,\"tenant\":\"456\",\"devciceIp\":\"789\",\"devciceId\":\"147\"},\"quInfo\":{\"account\":\"258\",\"pushId\":\"369\",\"optSys\":\"159\",\"code\":\"357\",\"addressProvince\":\"153\",\"addressRegion\":\"183\",\"businessType\":\"486\",\"addressCity\":\"759\",\"codeKey\":\"726\"} }");
    	postForObject(template, paramMap, url);
    	postForEntity(template, paramMap, url);
    	exchange(template, paramMap, url);
	}
	public static String postForObject(RestTemplate template,MultiValueMap<String, Object> paramMap,String url){
    	// 1、使用postForObject请求接口
    	String result = template.postForObject(url, paramMap, String.class);
    	System.out.println("result1==================" + result);
    	return result;
    }
	public static String postForEntity(RestTemplate template,MultiValueMap<String, Object> paramMap,String url){
    	HttpHeaders headers = new HttpHeaders();
    	HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
    	ResponseEntity<String> response2 = template.postForEntity(url, httpEntity, String.class);
    	System.out.println("result2====================" + response2.getBody());
    	return response2.getBody();
    }
	public static String exchange(RestTemplate template,MultiValueMap<String, Object> paramMap,String url) {
		HttpHeaders headers = new HttpHeaders();
    	HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<MultiValueMap<String, Object>>(paramMap,headers);
    	ResponseEntity<String> response3 = template.exchange(url, HttpMethod.POST, httpEntity, String.class);
		System.out.println("result3====================" + response3.getBody());
		return response3.getBody();
	}

猜你喜欢

转载自blog.csdn.net/qq_36364521/article/details/84203133