RestTemplate 是 Spring Restful Client 用於調用restful介面
package api.web; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.client.RestTemplate; import api.domain.City; import api.repository.CityRepository; @Controller public class IndexController { @Autowired private CityRepository repository; // Spring RESTFul Client @RequestMapping("/restful/get") @ResponseBody public String restfulGet() { RestTemplate restTemplate = new RestTemplate(); String text = restTemplate.getForObject("http://inf.netkiller.cn/detail/html/2/2/42564.html", String.class); return text; } @RequestMapping("/restful/get/{id}") @ResponseBody private static String restfulGetId(@PathVariable String id) { final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html"; Map<String, String> params = new HashMap<String, String>(); params.put("tid", "2"); params.put("cid", "2"); params.put("id", id); RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.getForObject(uri, String.class, params); return (result); } @RequestMapping("/restful/post/{id}") @ResponseBody private static String restfullPost(@PathVariable String id) { final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html"; Map<String, String> params = new HashMap<String, String>(); params.put("tid", "2"); params.put("cid", "2"); params.put("id", id); City city = new City("Shenzhen", "Guangdong"); RestTemplate restTemplate = new RestTemplate(); String result = restTemplate.postForObject(uri, city, String.class, params); return result; } @RequestMapping("/restful/put/{id}") private static void restfulPut(@PathVariable String id) { final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html"; Map<String, String> params = new HashMap<String, String>(); params.put("id", id); City city = new City("Shenzhen", "Guangdong"); RestTemplate restTemplate = new RestTemplate(); restTemplate.put(uri, city, params); } @RequestMapping("/restful/delete/{id}") private static void restfulDelete(@PathVariable String id) { final String uri = "http://inf.netkiller.cn/detail/html/{tid}/{cid}/{id}.html"; Map<String, String> params = new HashMap<String, String>(); params.put("id", id); RestTemplate restTemplate = new RestTemplate(); restTemplate.delete(uri, params); } }