1.基本介绍
Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多,
本次介绍三种:
1.HttpURLConnection实现
2.HttpClient实现
3.Spring的RestTemplate
2.HttpURLConnection实现
1 @Controller 2 public class RestfulAction { 3 4 @Autowired 5 private UserService userService; 6 7 // 修改 8 @RequestMapping(value = "put/{param}", method = RequestMethod.PUT) 9 public @ResponseBody String put(@PathVariable String param) { 10 return "put:" + param; 11 } 12 13 // 新增 14 @RequestMapping(value = "post/{param}", method = RequestMethod.POST) 15 public @ResponseBody String post(@PathVariable String param,String id,String name) { 16 System.out.println("id:"+id); 17 System.out.println("name:"+name); 18 return "post:" + param; 19 } 20 21 22 // 删除 23 @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE) 24 public @ResponseBody String delete(@PathVariable String param) { 25 return "delete:" + param; 26 } 27 28 // 查找 29 @RequestMapping(value = "get/{param}", method = RequestMethod.GET) 30 public @ResponseBody String get(@PathVariable String param) { 31 return "get:" + param; 32 } 33 34 35 // HttpURLConnection 方式调用Restful接口 36 // 调用接口 37 @RequestMapping(value = "dealCon/{param}") 38 public @ResponseBody String dealCon(@PathVariable String param) { 39 try { 40 String url = "http://localhost:8080/tao-manager-web/"; 41 url+=(param+"/xxx"); 42 URL restServiceURL = new URL(url); 43 HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL 44 .openConnection(); 45 //param 输入小写,转换成 GET POST DELETE PUT 46 httpConnection.setRequestMethod(param.toUpperCase()); 47 // httpConnection.setRequestProperty("Accept", "application/json"); 48 if("post".equals(param)){ 49 //打开输出开关 50 httpConnection.setDoOutput(true); 51