范文健康探索娱乐情感热点
投稿投诉
热点动态
科技财经
情感日志
励志美文
娱乐时尚
游戏搞笑
探索旅游
历史星座
健康养生
美丽育儿
范文作文
教案论文
国学影视

三种方法实现调用Restful接口

  1、基本介绍
  Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多,
  本次介绍三种:
  1)、HttpURLConnection实现
  2)、HttpClient实现
  3)、Spring的RestTemplate
  2、HTTPURLConnection实现 @Controller public class RestfulAction {      @Autowired     private UserService userService;      // 修改     @RequestMapping(value = "put/{param}", method = RequestMethod.PUT)     public @ResponseBody String put(@PathVariable String param) {         return "put:" + param;     }      // 新增     @RequestMapping(value = "post/{param}", method = RequestMethod.POST)     public @ResponseBody String post(@PathVariable String param,String id,String name) {         System.out.println("id:"+id);         System.out.println("name:"+name);         return "post:" + param;     }      // 删除     @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)     public @ResponseBody String delete(@PathVariable String param) {         return "delete:" + param;     }      // 查找     @RequestMapping(value = "get/{param}", method = RequestMethod.GET)     public @ResponseBody String get(@PathVariable String param) {         return "get:" + param;     }      // HttpURLConnection 方式调用Restful接口     // 调用接口     @RequestMapping(value = "dealCon/{param}")     public @ResponseBody String dealCon(@PathVariable String param) {         try {             String url = "http://localhost:8080/tao-manager-web/";             url+=(param+"/xxx");             URL restServiceURL = new URL(url);             HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL                     .openConnection();             //param 输入小写,转换成 GET POST DELETE PUT             httpConnection.setRequestMethod(param.toUpperCase()); //            httpConnection.setRequestProperty("Accept", "application/json");             if("post".equals(param)){                 //打开输出开关                 httpConnection.setDoOutput(true); //                httpConnection.setDoInput(true);                  //传递参数                 String input = "&id="+ URLEncoder.encode("abc", "UTF-8");                 input+="&name="+ URLEncoder.encode("啊啊啊", "UTF-8");                 OutputStream outputStream = httpConnection.getOutputStream();                 outputStream.write(input.getBytes());                 outputStream.flush();             }             if (httpConnection.getResponseCode() != 200) {                 throw new RuntimeException(                         "HTTP GET Request Failed with Error code : "                                 + httpConnection.getResponseCode());             }             BufferedReader responseBuffer = new BufferedReader(                     new InputStreamReader((httpConnection.getInputStream())));             String output;             System.out.println("Output from Server:   ");             while ((output = responseBuffer.readLine()) != null) {                 System.out.println(output);             }             httpConnection.disconnect();         } catch (MalformedURLException e) {             e.printStackTrace();         } catch (IOException e) {             e.printStackTrace();         }         return "success";     }  }
  3、HttpClient实现 package com.taozhiye.controller;  import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; 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.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody;  import com.fasterxml.jackson.databind.ObjectMapper; import com.taozhiye.entity.User; import com.taozhiye.service.UserService;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.List;  @Controller public class RestfulAction {      @Autowired     private UserService userService;      // 修改     @RequestMapping(value = "put/{param}", method = RequestMethod.PUT)     public @ResponseBody String put(@PathVariable String param) {         return "put:" + param;     }      // 新增     @RequestMapping(value = "post/{param}", method = RequestMethod.POST)     public @ResponseBody User post(@PathVariable String param,String id,String name) {         User u = new User();         System.out.println(id);         System.out.println(name);         u.setName(id);         u.setPassword(name);         u.setEmail(id);         u.setUsername(name);         return u;     }      // 删除     @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)     public @ResponseBody String delete(@PathVariable String param) {         return "delete:" + param;     }      // 查找     @RequestMapping(value = "get/{param}", method = RequestMethod.GET)     public @ResponseBody User get(@PathVariable String param) {         User u = new User();         u.setName(param);         u.setPassword(param);         u.setEmail(param);         u.setUsername("爱爱啊");         return u;     }      @RequestMapping(value = "dealCon2/{param}")     public @ResponseBody User dealCon2(@PathVariable String param) {         User user = null;         try {             HttpClient client = HttpClients.createDefault();             if("get".equals(param)){                 HttpGet request = new HttpGet("http://localhost:8080/tao-manager-web/get/"                         +"啊啊啊");                 request.setHeader("Accept", "application/json");                 HttpResponse response = client.execute(request);                 HttpEntity entity = response.getEntity();                 ObjectMapper mapper = new ObjectMapper();                 user = mapper.readValue(entity.getContent(), User.class);             }else if("post".equals(param)){                 HttpPost request2 = new HttpPost("http://localhost:8080/tao-manager-web/post/xxx");                 List nvps = new ArrayList();                 nvps.add(new BasicNameValuePair("id", "啊啊啊"));                 nvps.add(new BasicNameValuePair("name", "secret"));                 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, "GBK");                 request2.setEntity(formEntity);                 HttpResponse response2 = client.execute(request2);                 HttpEntity entity = response2.getEntity();                 ObjectMapper mapper = new ObjectMapper();                 user = mapper.readValue(entity.getContent(), User.class);             }else if("delete".equals(param)){              }else if("put".equals(param)){              }         } catch (Exception e) {             e.printStackTrace();         }         return user;     } }
  4、String的RestTemplate实现
  springmvc.xml增加                                                          
  controller@Controller public class RestTemplateAction {      @Autowired     private RestTemplate template;      @RequestMapping("RestTem")     public @ResponseBody User RestTem(String method) {         User user = null;         //查找         if ("get".equals(method)) {             user = template.getForObject(                     "http://localhost:8080/tao-manager-web/get/{id}",                     User.class, "呜呜呜呜");              //getForEntity与getForObject的区别是可以获取返回值和状态、头等信息             ResponseEntity re = template.                     getForEntity("http://localhost:8080/tao-manager-web/get/{id}",                     User.class, "呜呜呜呜");             System.out.println(re.getStatusCode());             System.out.println(re.getBody().getUsername());          //新增         } else if ("post".equals(method)) {             HttpHeaders headers = new HttpHeaders();             headers.add("X-Auth-Token", UUID.randomUUID().toString());             MultiValueMap postParameters = new LinkedMultiValueMap();             postParameters.add("id", "啊啊啊");             postParameters.add("name", "部版本");             HttpEntity> requestEntity = new HttpEntity>(                     postParameters, headers);             user = template.postForObject(                     "http://localhost:8080/tao-manager-web/post/aaa", requestEntity,                     User.class);         //删除         } else if ("delete".equals(method)) {             template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");         //修改         } else if ("put".equals(method)) {             template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");         }         return user;      } }

华为nove7se新版即将上市华为nova7SE新版本要上市了,屏幕镜头以及它的机身数值都没变,唯一有区别的就是处理器从麒麟820换成主频2。4GHz的天玑800U。变化是4个高频A76换成2个高频A76,6核还在为电脑系统卡慢而烦恼吗?新版win10重点优化这个问题Hello大家好,我是兼容机之家的小牛!自从Windows102015年正式发布以来,已经过去快五年的时间,在这五年的时间里,Windows10从一个BUG超多的难用的系统,已经转好多人都踩过的坑,同一道题,电脑手机却算出两种不同的结果!Hello大家好,我是兼容机之家的小牛!从前有个老板,经常用手机里面的计算器算账,注意不是电脑Windows系统里面的计算器。但是总是算不对,实际上是盈利的,可是他总是算出了亏本。手机成本统计报告,揭秘哪个品牌才是溢价之王,结果令人没有想到Hello大家好,我是兼容机之家的小牛!昨天小米发布了RedmiK30Pro,明天华为要发布旗舰级产品P40系列,今天夹在中间很是为难。不知道大家发现了没有,因为不可抗力的原因,M手机行业高利润被打破,苹果影响最大,只因这张小小的超级SIM卡Hello大家好,我是兼容机之家的小牛!近些年来,智能手机的发展异常迅猛。从三星HTC安卓双星争霸,到后来的中华酷联低价时代,再到如今国产手机百花齐放的局面。国内市场已经摆脱了被三电脑进不了系统,送来检查只是小问题,但主机配置却引起我的注意Hello大家好,我是兼容机之家的小牛!今天有个本地网友拿台电脑主机上门,说自己系统进不去,让我看看是不是电脑有问题。其实就是一个简单的系统问题,三下五除二就搞定了。电脑进不了系统P40发布后,让咱看看手机疯狂涨价的背后,到底是谁在控制着涨价Hello大家好,我是兼容机之家的小牛!昨晚华为P40发布,宣布着年初各家的旗舰手机基本上都发布完毕了,接下来的新机莫过于4月份的iPhone9最值得期待了。其中,华为P40系列国苹果又一款新手机视频曝光,全新四摄加金属中框,价格或有惊喜Hello大家好,我是兼容机之家的小牛!前两天,华为发布全新的P40系列手机,从低到高一共三款手机,分别是P40P40ProP40Pro。这三款手机的最大不同的地方就在后置摄像头的昨日华为连发三款旗舰手机,麒麟990性能堪比P40,价格仅2999起Hello大家好,我是兼容机之家的小牛!继华为旗舰手机P40系列发布之后,华为上半年的第二部旗舰手机荣耀30终于来了。不同于华为P40系列那高昂的价格,同样搭载麒麟9905G芯片的资本实验室与远望智库联合发布2021全球区块链应用市场报告从以比特币为代表的区块链1。0时代到以智能合约为媒介,以金融应用为核心的区块链2。0时代再到区块链应用于政务服务和更广泛的各行业,并开始推动信息互联网向价值互联网靠拢,短短10余年开挂的特斯拉季度交付量创纪录,市值位居全球第七据特斯拉最新公布的2021年第三季度汽车生产和交付数据,公司在三季度的交付量超过240,000辆,创下新的季度交付记录,前三季度总交付量已超过627,000辆。从季度分布来看,特斯
降速门再现?传系统更新后部分iPhone12性能不如iPhoneXR品玩5月10日讯,苹果近日悄悄推送了iOS14。5。1正式版,但是不少用户表示,安装了最新版系统的消费者发现,他们手中的iPhone似乎出现了性能衰减。iPhone11iPhone华为鸿蒙系统2。0第二轮公测名单出炉,新增七款机型,有你的吗?华为鸿蒙系统第一轮公测的机型有华为Mate40系列,P40系列Mate30系列MatePadPro系列以及华为智慧屏S系列等机型。在第二轮公测名单中,新增加Nova6系列Nova7手机UI排行榜无MIUI,系统流畅榜也没有小米?大家都知道安卓手机UI一直是MIUI的口碑比较高,也有很多米粉都说用了离不开,但是在最新的鲁大师手机UI排行榜上却看不到MIUI的身影,我还以为是排斥小米不放上去呢,后来看了下是因安卓用户笑了!iPhone12更新系统后,性能倒退3年点击右上方关注,第一时间获取科技资讯技能攻略产品体验,私信我回复01,送你一份玩机技能大礼包。不知道大家还记不记得2019年前后,闹得沸沸扬扬的苹果降速门?简单来说,就是苹果会在系华为开发者重磅回击!鸿蒙不是安卓的替代,系统内核将颠覆认知最近,华为鸿蒙系统推出公测版,然而却有许多人质疑,HarmonyOS是安卓的替代品,罗叔不知道他们到底用没用过,huawei手机的新系统,但是最近鸿蒙系统的开发者,对这些流言进行了荣耀系列又迎来利好!华为鸿蒙OS2。0第二轮公测开启再增加7款机型今年4月底鸿蒙OS2。0正式开启公测,第一批已经完成了华为Mate40系列华为Mate30系列华为P40系列华为MatePadPro以及华为智慧屏S系列等17款机型。而很多用户升级中国有多少人玩比特币?人还不少,具体数字还真不好统计!很多非常多国家政策不允许交易,现在还能玩吗?至少500万这个问题不错,玩比特币的还真不少。先前比特币不值钱,后来炒成了天价。玩家成千倍赚的盆满钵满,打算7千买个手机,是选苹果还是华为?大家给个意见?选华为,你不会后悔的。苹果手机目前没有通话录音功能抠鼻别告诉我你不需要,有些时候录音键还是很有用的自己考虑,一个是自己买的一个是单位配的首选华为手机二选华为手机再选华为手机必须支持金蝶董事长徐少春卡脖子的不是技术而是思维模式中国青年报讯(中青报中青网记者李晨赫)金蝶砸掉的不是卡脖子的手,而是禁锢我们思维模式的牢笼。5月8日,在2021金蝶云苍穹峰会上,金蝶集团董事会主席兼CEO徐少春与一众参会嘉宾,抡7年12个大版本,Win10都更新了些啥?你还会期待Win10大版本更新吗?2014年10月1日,微软正式公布Windows10操作系统。在受到iOSAndroid等移动设备的冲击,并且经历了Windows88。1的屡次失官宣周鸿祎再次出场,360与哪吒汽车合作造车文懂车帝原创邢秋鸿懂车帝原创行业疯狂的造车运动还没有停止,这次轮到了360集团和周鸿祎。5月10日下午,360公司官网发布消息人民想念的周鸿祎即将再一次出场啦,这一次又将给行业带来