GET请求
import org.springframework.web.client.RestTemplate;
@Resource
RestTemplate restTemplate;
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
httpRequestFactory.setConnectionRequestTimeout(10000);
httpRequestFactory.setConnectTimeout(10000);
httpRequestFactory.setReadTimeout(10000);
return new RestTemplate(httpRequestFactory);
}
@Override
public List<SysStudent> getListInfo() throws Exception {
Map<String, Object> json=new HashMap<>();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
Map<String,Object> params = new HashMap<>();
params.put("phoneNumber",phoneNumber);
restTemplate.getForObject("http://192.168.2.136:8080/api/list?phoneNumber={phoneNumber}",String.class,params);
return null;
}
POST请求
public String post(Student student) {
Map<String, Object> json = new HashMap<>();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_JSON);
HttpEntity entity = new HttpEntity(student, requestHeaders);
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
String result = null;
try{
result = restTemplate.postForObject("http://192.168.2.136:8080/api/complete",entity, String.class));
}catch (Exception e){
log.info("请求失败",e);
}
return result;
}