三种方法实现调用Restful接口

本文介绍了前端使用ajax调用Restful接口,后端则通过HttpURLConnection、HttpClient和Spring的RestTemplate三种方式进行调用的方法。详细讲解了每种方式的实现步骤,并提供了配置示例。
摘要由CSDN通过智能技术生成

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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值