RestTemplate是spring提供的用于訪問Rest服務(wù)的客戶端,RestTemplate提供了多種便捷訪問遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶端的編寫效率。
調(diào)用RestTemplate的默認(rèn)構(gòu)造函數(shù),RestTemplate對象在底層通過使用Java.net包下的實(shí)現(xiàn)創(chuàng)建HTTP 請求,可以通過使用ClientHttpRequestFactory指定不同的HTTP請求方式。ClientHttpRequestFactory接口主要提供了兩種實(shí)現(xiàn)方式:
一種是SimpleClientHttpRequestFactory,使用J2SE提供的方式(既java.net包提供的方式)創(chuàng)建底層的Http請求連接。
一種方式是使用HttpComponentsClientHttpRequestFactory方式,底層使用HttpClient訪問遠(yuǎn)程的Http服務(wù),使用HttpClient可以配置連接池和證書等信息。[本段抄]
本文使用SimpleClientHttpRequestFactory實(shí)現(xiàn)ClientHttpRequestFactory接口
public class SimpleRestClient {
private static RestTemplate restTemplate;
private SimpleRestClient() {
}
static {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(15000);
factory.setConnectTimeout(15000);
restTemplate = new RestTemplate(factory);
CustomHttpMessageConverter converter = new CustomHttpMessageConverter();
List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
converters.add(converter);
restTemplate.setMessageConverters(converters);
}
public static RestTemplate getClient() {
return restTemplate;
}
}
get方式
//Object 對象為Response返回的具體類型,需根據(jù)實(shí)際返回對象創(chuàng)建實(shí)體類等
//參數(shù)直接放在URL中
Object result = restTemplate.getForObject("http://localhost:8080/xxx/test?appid=1", Object.class);
// 參數(shù)使用可變參數(shù) ...
int appid = 1;
Object result = restTemplate.getForObject("http://localhost:8080/xxx/test?appid={appid}", Object.class, appid);
//參數(shù)使用MAP傳遞
Map<String,Object> urlVariables = new HashMap<String,Object>();
urlVariables.put("appid", 1);
Object result = restTemplate.getForObject("http://localhost:8080/xxx/test", Object.class, urlVariables);
post方式
//postForObject 使用方式與get基本相同
Object result = restTemplate
.postForObject("http://localhost:8080/xxx/test", null, UmBenefitRuleResponse.class);
put方式
//參數(shù)同上三種方式
restTemplate.put("http://localhost:8080/xxx/test" ,null);
delete方式
//參數(shù)同上三種方式
restTemplate.delete("http://localhost:8080/xxx/test?appid={appid}",appid);
推薦博文:RestTemplate實(shí)踐