三种方法实现调用Restful接口

简介: 1.基本介绍  Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法比较多,  本次介绍三种:    1.HttpURLConnection实现    2.HttpClient实现    3.

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 //                httpConnection.setDoInput(true);
52                 
53                 //传递参数
54                 String input = "&id="+ URLEncoder.encode("abc", "UTF-8");
55                 input+="&name="+ URLEncoder.encode("啊啊啊", "UTF-8");
56                 OutputStream outputStream = httpConnection.getOutputStream();
57                 outputStream.write(input.getBytes());
58                 outputStream.flush();
59             }
60             if (httpConnection.getResponseCode() != 200) {
61                 throw new RuntimeException(
62                         "HTTP GET Request Failed with Error code : "
63                                 + httpConnection.getResponseCode());
64             }
65             BufferedReader responseBuffer = new BufferedReader(
66                     new InputStreamReader((httpConnection.getInputStream())));
67             String output;
68             System.out.println("Output from Server:  \n");
69             while ((output = responseBuffer.readLine()) != null) {
70                 System.out.println(output);
71             }
72             httpConnection.disconnect();
73         } catch (MalformedURLException e) {
74             e.printStackTrace();
75         } catch (IOException e) {
76             e.printStackTrace();
77         }
78         return "success";
79     }
80 
81 }
复制代码

 

 

 

3.HttpClient实现

复制代码
  1 package com.taozhiye.controller;
  2 
  3 import org.apache.http.HttpEntity;
  4 import org.apache.http.HttpResponse;
  5 import org.apache.http.NameValuePair;
  6 import org.apache.http.client.HttpClient;
  7 import org.apache.http.client.entity.UrlEncodedFormEntity;
  8 import org.apache.http.client.methods.HttpDelete;
  9 import org.apache.http.client.methods.HttpGet;
 10 import org.apache.http.client.methods.HttpPost;
 11 import org.apache.http.client.methods.HttpPut;
 12 import org.apache.http.impl.client.HttpClients;
 13 import org.apache.http.message.BasicNameValuePair;
 14 import org.springframework.beans.factory.annotation.Autowired;
 15 import org.springframework.stereotype.Controller;
 16 import org.springframework.web.bind.annotation.PathVariable;
 17 import org.springframework.web.bind.annotation.RequestMapping;
 18 import org.springframework.web.bind.annotation.RequestMethod;
 19 import org.springframework.web.bind.annotation.ResponseBody;
 20 
 21 import com.fasterxml.jackson.databind.ObjectMapper;
 22 import com.taozhiye.entity.User;
 23 import com.taozhiye.service.UserService;
 24 
 25 import java.io.BufferedReader;
 26 import java.io.IOException;
 27 import java.io.InputStreamReader;
 28 import java.io.OutputStream;
 29 import java.net.HttpURLConnection;
 30 import java.net.MalformedURLException;
 31 import java.net.URL;
 32 import java.net.URLEncoder;
 33 import java.util.ArrayList;
 34 import java.util.List;
 35 
 36 @Controller
 37 public class RestfulAction {
 38     
 39     @Autowired
 40     private UserService userService;
 41 
 42     // 修改
 43     @RequestMapping(value = "put/{param}", method = RequestMethod.PUT)
 44     public @ResponseBody String put(@PathVariable String param) {
 45         return "put:" + param;
 46     }
 47 
 48     // 新增
 49     @RequestMapping(value = "post/{param}", method = RequestMethod.POST)
 50     public @ResponseBody User post(@PathVariable String param,String id,String name) {
 51         User u = new User();
 52         System.out.println(id);
 53         System.out.println(name);
 54         u.setName(id);
 55         u.setPassword(name);
 56         u.setEmail(id);
 57         u.setUsername(name);
 58         return u;
 59     }
 60     
 61 
 62     // 删除
 63     @RequestMapping(value = "delete/{param}", method = RequestMethod.DELETE)
 64     public @ResponseBody String delete(@PathVariable String param) {
 65         return "delete:" + param;
 66     }
 67 
 68     // 查找
 69     @RequestMapping(value = "get/{param}", method = RequestMethod.GET)
 70     public @ResponseBody User get(@PathVariable String param) {
 71         User u = new User();
 72         u.setName(param);
 73         u.setPassword(param);
 74         u.setEmail(param);
 75         u.setUsername("爱爱啊");
 76         return u;
 77     }
 78 
 79     
 80     
 81     @RequestMapping(value = "dealCon2/{param}")
 82     public @ResponseBody User dealCon2(@PathVariable String param) {
 83         User user = null;
 84         try {
 85             HttpClient client = HttpClients.createDefault();
 86             if("get".equals(param)){
 87                 HttpGet request = new HttpGet("http://localhost:8080/tao-manager-web/get/"
 88                         +"啊啊啊");
 89                 request.setHeader("Accept", "application/json");
 90                 HttpResponse response = client.execute(request);
 91                 HttpEntity entity = response.getEntity();
 92                 ObjectMapper mapper = new ObjectMapper();
 93                 user = mapper.readValue(entity.getContent(), User.class);
 94             }else if("post".equals(param)){
 95                 HttpPost request2 = new HttpPost("http://localhost:8080/tao-manager-web/post/xxx");
 96                 List<NameValuePair> nvps = new ArrayList<NameValuePair>();  
 97                 nvps.add(new BasicNameValuePair("id", "啊啊啊"));  
 98                 nvps.add(new BasicNameValuePair("name", "secret"));
 99                 UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvps, "GBK");
100                 request2.setEntity(formEntity);
101                 HttpResponse response2 = client.execute(request2);
102                 HttpEntity entity = response2.getEntity();
103                 ObjectMapper mapper = new ObjectMapper();
104                 user = mapper.readValue(entity.getContent(), User.class);
105             }else if("delete".equals(param)){
106                 
107             }else if("put".equals(param)){
108                 
109             }
110         } catch (Exception e) {
111             e.printStackTrace();
112         }
113         return user;
114     }
115     
116     
117 }
复制代码

 

4.Spring的RestTemplate

springmvc.xml增加

复制代码
 1     <!-- 配置RestTemplate -->
 2     <!--Http client Factory -->
 3     <bean id="httpClientFactory"
 4         class="org.springframework.http.client.SimpleClientHttpRequestFactory">
 5         <property name="connectTimeout" value="10000" />
 6         <property name="readTimeout" value="10000" />
 7     </bean>
 8 
 9     <!--RestTemplate -->
10     <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
11         <constructor-arg ref="httpClientFactory" />
12     </bean>
复制代码

controller

复制代码
 1 @Controller
 2 public class RestTemplateAction {
 3 
 4     @Autowired
 5     private RestTemplate template;
 6 
 7     @RequestMapping("RestTem")
 8     public @ResponseBody User RestTem(String method) {
 9         User user = null;
10         //查找
11         if ("get".equals(method)) {
12             user = template.getForObject(
13                     "http://localhost:8080/tao-manager-web/get/{id}",
14                     User.class, "呜呜呜呜");
15             
16             //getForEntity与getForObject的区别是可以获取返回值和状态、头等信息
17             ResponseEntity<User> re = template.
18                     getForEntity("http://localhost:8080/tao-manager-web/get/{id}",
19                     User.class, "呜呜呜呜");
20             System.out.println(re.getStatusCode());
21             System.out.println(re.getBody().getUsername());
22             
23         //新增
24         } else if ("post".equals(method)) {
25             HttpHeaders headers = new HttpHeaders();
26             headers.add("X-Auth-Token", UUID.randomUUID().toString());
27             MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
28             postParameters.add("id", "啊啊啊");
29             postParameters.add("name", "部版本");
30             HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
31                     postParameters, headers);
32             user = template.postForObject(
33                     "http://localhost:8080/tao-manager-web/post/aaa", requestEntity,
34                     User.class);
35         //删除
36         } else if ("delete".equals(method)) {
37             template.delete("http://localhost:8080/tao-manager-web/delete/{id}","aaa");
38         //修改
39         } else if ("put".equals(method)) {
40             template.put("http://localhost:8080/tao-manager-web/put/{id}",null,"bbb");
41         }
42         return user;
43 
44     }
45 }
复制代码

 

相关文章
|
XML 缓存 JSON
前后端分离开发,RESTful 接口应该这样设计
前后端分离开发,RESTful 接口应该这样设计
668 0
前后端分离开发,RESTful 接口应该这样设计
|
11月前
|
缓存 安全 API
RESTful与GraphQL:电商API接口设计的技术细节与适用场景
本文对比了RESTful与GraphQL这两种主流电商API接口设计方案。RESTful通过资源与HTTP方法定义操作,简单直观但可能引发过度或欠获取数据问题;GraphQL允许客户端精确指定所需字段,提高灵活性和传输效率,但面临深度查询攻击等安全挑战。从性能、灵活性、安全性及适用场景多维度分析,RESTful适合资源导向场景,GraphQL则适用于复杂数据需求。实际开发中需根据业务特点选择合适方案,或结合两者优势,以优化用户体验与系统性能。
|
11月前
|
JSON 编解码 API
Go语言网络编程:使用 net/http 构建 RESTful API
本章介绍如何使用 Go 语言的 `net/http` 标准库构建 RESTful API。内容涵盖 RESTful API 的基本概念及规范,包括 GET、POST、PUT 和 DELETE 方法的实现。通过定义用户数据结构和模拟数据库,逐步实现获取用户列表、创建用户、更新用户、删除用户的 HTTP 路由处理函数。同时提供辅助函数用于路径参数解析,并展示如何设置路由器启动服务。最后通过 curl 或 Postman 测试接口功能。章节总结了路由分发、JSON 编解码、方法区分、并发安全管理和路径参数解析等关键点,为更复杂需求推荐第三方框架如 Gin、Echo 和 Chi。
|
XML JSON API
Understanding RESTful API and Web Services: Key Differences and Use Cases
在现代软件开发中,RESTful API和Web服务均用于实现系统间通信,但各有特点。RESTful API遵循REST原则,主要使用HTTP/HTTPS协议,数据格式多为JSON或XML,适用于无状态通信;而Web服务包括SOAP和REST,常用于基于网络的API,采用标准化方法如WSDL或OpenAPI。理解两者区别有助于选择适合应用需求的解决方案,构建高效、可扩展的应用程序。
|
机器学习/深度学习 设计模式 API
Python 高级编程与实战:构建 RESTful API
本文深入探讨了使用 Python 构建 RESTful API 的方法,涵盖 Flask、Django REST Framework 和 FastAPI 三个主流框架。通过实战项目示例,详细讲解了如何处理 GET、POST 请求,并返回相应数据。学习这些技术将帮助你掌握构建高效、可靠的 Web API。
|
JSON 缓存 JavaScript
深入浅出:使用Node.js构建RESTful API
在这个数字时代,API已成为软件开发的基石之一。本文旨在引导初学者通过Node.js和Express框架快速搭建一个功能完备的RESTful API。我们将从零开始,逐步深入,不仅涉及代码编写,还包括设计原则、最佳实践及调试技巧。无论你是初探后端开发,还是希望扩展你的技术栈,这篇文章都将是你的理想指南。
|
JSON JavaScript 前端开发
深入浅出Node.js:从零开始构建RESTful API
在数字化时代的浪潮中,后端开发作为连接用户与数据的桥梁,扮演着至关重要的角色。本文将引导您步入Node.js的奇妙世界,通过实践操作,掌握如何使用这一强大的JavaScript运行时环境构建高效、可扩展的RESTful API。我们将一同探索Express框架的使用,学习如何设计API端点,处理数据请求,并实现身份验证机制,最终部署我们的成果到云服务器上。无论您是初学者还是有一定基础的开发者,这篇文章都将为您打开一扇通往后端开发深层知识的大门。
418 12
|
XML JSON 缓存
深入理解RESTful API设计原则与实践
在现代软件开发中,构建高效、可扩展的应用程序接口(API)是至关重要的。本文旨在探讨RESTful API的核心设计理念,包括其基于HTTP协议的特性,以及如何在实际应用中遵循这些原则来优化API设计。我们将通过具体示例和最佳实践,展示如何创建易于理解、维护且性能优良的RESTful服务,从而提升前后端分离架构下的开发效率和用户体验。
|
监控 安全 API
深入浅出:构建高效RESTful API的最佳实践
在数字化时代,API已成为连接不同软件和服务的桥梁。本文将带你深入了解如何设计和维护一个高效、可扩展且安全的RESTful API。我们将从基础概念出发,逐步深入到高级技巧,让你能够掌握创建优质API的关键要素。无论你是初学者还是有经验的开发者,这篇文章都将为你提供实用的指导和启示。让我们一起探索API设计的奥秘,打造出色的后端服务吧!
|
JSON 缓存 测试技术
构建高效RESTful API的后端实践指南####
本文将深入探讨如何设计并实现一个高效、可扩展且易于维护的RESTful API。不同于传统的摘要概述,本节将直接以行动指南的形式,列出构建RESTful API时必须遵循的核心原则与最佳实践,旨在为开发者提供一套直接可行的实施框架,快速提升API设计与开发能力。 ####