@Configuration
public class ApplicationContextConfig {
@Bean // applicationContext.xml <bean id="" class="">
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "/consumer/payment/create")
public CommonResult<Payment> create(Payment payment) {
return restTemplate.postForObject(“http://localhost:8080” + "/payment/get/" + id, payment, CommonResult.class);
// (url, requestMap, ResponseBean.class) 这三个参数分别代表
// REST请求地址、请求参数、HTTP响应被转换成的对象类型
// 支持的方法很多,不一一列举了
}
@GetMapping(value = "/consumer/payment/getForEntity/{id}")
public CommonResult getpaymentlist2(@PathVariable("id") Long id) {
ResponseEntity<CommonResult> entity = restTemplate.getForEntity(PAYMENT_URL + "/payment/get/" + id, CommonResult.class);
if (entity.getStatusCode().is2xxSuccessful()){
// log.info(entity.getHeaders());
return entity.getBody();
}else {
return new CommonResult(444,"查询失败");
}
}
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
private static String formUpload(){
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set("token","123");
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 封装参数,千万不要替换为Map与HashMap,否则参数无法传递
MultiValueMap<String, Object> multiValueMap = new LinkedMultiValueMap<>();
multiValueMap.add("api_key", API_KEY);
multiValueMap.add("api_secret", API_SECRET);
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multiValueMap, httpHeaders);
return restTemplate.postForObject(serverUrl, httpEntity, String.class);
}