簡(jiǎn)介
RestTemplate是Spring的模板類,在客戶端上可以使用該類調(diào)用Web服務(wù)器端的服務(wù),它支持REST風(fēng)格的URL短条。在Spring中有許多類似功能的類,如JdbcTemplate, JmsTemplate等才菠。
RestTemplate可以用GET方法來獲取資源茸时,或者用POST方法來創(chuàng)建資源。
postForObject
1. post HttpEntity
postForObject本質(zhì)上是將對(duì)象放入HttpEntity中赋访,然后將對(duì)象POST給一個(gè)url可都,下面代碼中所示的使用方法是最典型的一種:
ClientHttpRequestFactory requestFactory = getClientHttpRequestFactory();
RestTemplate restTemplate = new RestTemplate(requestFactory);
HttpEntity<Foo> request = new HttpEntity<>(new Foo("bar"));//將對(duì)象裝入HttpEntity中
Foo foo = restTemplate.postForObject(fooResourceUrl, request, Foo.class);
2. post JavaObject
實(shí)際上,如果不人為的將對(duì)象放入HttpEntity中蚓耽,也可以直接使用RestTemplate去POST一個(gè)對(duì)象:
Foo foo = new Foo("bar");
Foo foo = restTemplate.postForObject(fooResourceUrl, foo, Foo.class);
可以這么做的原因是,在RestTemplate的代碼中汹粤,專門有一部分進(jìn)行了POST對(duì)象的類型檢測(cè)和轉(zhuǎn)換 :
if (requestBody instanceof HttpEntity) {
this.requestEntity = (HttpEntity<?>) requestBody;
}
else if (requestBody != null) {
this.requestEntity = new HttpEntity<Object>(requestBody);
}
else {
this.requestEntity = HttpEntity.EMPTY;
}
3. post JSON
如果需要post的對(duì)象是以JSON形式存儲(chǔ),則需要手動(dòng)將JSON字符串轉(zhuǎn)化成HttpEntity田晚,具體做法如下:
String jsonString = "{\"id\":10,\"name\":\"test\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf("application/json;UTF-8"));
HttpEntity<String> strEntity = new HttpEntity<String>(jsonString,headers);
RestTemplate restTemplate = new RestTemplate();
Foo foo = restTemplate.postForObject(url,strEntity,Foo.class);
System.out.println(jo2);
URI編碼注意事項(xiàng)
無論是GET還是POST嘱兼,RestTemplate的方法的第一個(gè)參數(shù)是String URI或java.net.URI
類型,需要注意的是:
1. 編碼(encode)
URI涉及到編碼問題贤徒,是因?yàn)橛行┳址麜?huì)引起歧義芹壕。比如參數(shù)中的key=value鍵值對(duì),當(dāng)value里含有= & ? 等接奈,就會(huì)造成 URL 服務(wù)器的解析錯(cuò)誤踢涌。所以必須將引起歧義的符號(hào)進(jìn)行轉(zhuǎn)義,也就是對(duì)其進(jìn)行編碼序宦。
如果使用String URI睁壁,那么其默認(rèn)是不編碼的,例如:
restTemplate.getForObject("http://example.com/hotel list", String.class);
RestTemplate會(huì)將URI轉(zhuǎn)化成http://example.com/hotel%20list
互捌,而如果畫蛇添足的向RestTemplate方法中傳入一個(gè)encode的String URI:
restTemplate.getForObject("http://example.com/hotel%20list", String.class);
那么該URI將會(huì)被加密兩次潘明,成為http://example.com/hotel%2520list
,而java.net.URI
默認(rèn)是編碼的秕噪,RestTemplate默認(rèn)是不編碼的钳降。
2. java.net.URI的使用
因?yàn)?code>java.net.URI提供了多種常用的URI加工方法,如果要多次使用同一個(gè)url腌巾,最好將其轉(zhuǎn)化成java.net.URI
遂填。
參考文獻(xiàn):
The Guide to RestTemplate
Java測(cè)試-RestTemplate-@requestBody
Spring Doc - RestTemplate