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 }

三种方法实现调用Restful接口的更多相关文章

  1. 三种方法实现java调用Restful接口

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

  2. (转)JAVA 调用Web Service的三种方法

    1.使用HttpClient用到的jar文件:commons-httpclient-3.1.jar方法:预先定义好Soap请求数据,可以借助于XMLSpy Professional软件来做这一步生成. ...

  3. 服务器文档下载zip格式 SQL Server SQL分页查询 C#过滤html标签 EF 延时加载与死锁 在JS方法中返回多个值的三种方法(转载) IEnumerable,ICollection,IList接口问题 不吹不擂,你想要的Python面试都在这里了【315+道题】 基于mvc三层架构和ajax技术实现最简单的文件上传 事件管理

    服务器文档下载zip格式   刚好这次项目中遇到了这个东西,就来弄一下,挺简单的,但是前台调用的时候弄错了,浪费了大半天的时间,本人也是菜鸟一枚.开始吧.(MVC的) @using Rattan.Co ...

  4. Second Day: 关于Button监听事件的三种方法(匿名类、外部类、继承接口)

    第一种:通过匿名类实现对Button事件的监听 首先在XML文件中拖入一个Button按钮,并设好ID,其次在主文件.java中进行控件初始化(Private声明),随后通过SetOnClickLis ...

  5. YbSoftwareFactory 代码生成插件【二十五】:Razor视图中以全局方式调用后台方法输出页面代码的三种方法

    上一篇介绍了 MVC中实现动态自定义路由 的实现,本篇将介绍Razor视图中以全局方式调用后台方法输出页面代码的三种方法. 框架最新的升级实现了一个页面部件功能,其实就是通过后台方法查询数据库内容,把 ...

  6. go 调用windows dll 的三种方法

    参考:https://blog.csdn.net/qq_39584315/article/details/81287669 大部分代码参考:https://studygolang.com/articl ...

  7. wordpress调用置顶文章sticky_posts的三种方法

    有时我们在开发wordpress时需要调用置顶文章sticky_posts,怎么调用呢?几种写法,有用到query_post的,有用到WP_Query,也有用到is_sticky(),下面随ytkah ...

  8. python网络编程调用recv函数完整接收数据的三种方法

    最近在使用python进行网络编程开发一个通用的tcpclient测试小工具.在使用socket进行网络编程中,如何判定对端发送一条报文是否接收完成,是进行socket网络开发必须要考虑的一个问题.这 ...

  9. Java调用RestFul接口

    使用Java调用RestFul接口,以POST请求为例,以下提供几种方法: 一.通过HttpURLConnection调用 1 public String postRequest(String url ...

随机推荐

  1. gin+gorm

    在[环境变量]中添加如下[用户变量]/[系统变量]:GO111MODULE,值为on go mod init目录 在项目中新建文件main.go,并添加测试代码 package main import ...

  2. 迷茫<第四篇:这两年>

    时间匆匆而过,不知不觉已经是到北京的第二个年头,又到年末,2017年接近了尾声,提前预祝各位看官元旦节快乐! 今年3月份跳槽了一次,4月份以高级开发工程师职位进来现在的公司一直工作到现在,没有以前那么 ...

  3. Java数据结构和算法 - 栈和队列

    Q: 栈.队列与数组的区别? A: 本篇主要涉及三种数据存储类型:栈.队列和优先级队列,它与数组主要有如下三个区别: A: (一)程序员工具 数组和其他的结构(栈.队列.链表.树等等)都适用于数据库应 ...

  4. C# 中的Async 和 Await 的用法详解

    众所周知C#提供Async和Await关键字来实现异步编程.在本文中,我们将共同探讨并介绍什么是Async 和 Await,以及如何在C#中使用Async 和 Await. 同样本文的内容也大多是翻译 ...

  5. 使用chan的时候选择对象还是指针

    使用chan的时候选择对象还是指针 今天在写代码的时候遇到一个问题,在创建一个通道的时候,不确定创建的通道是使用chan A还是chan *A. 思考了一下,觉得这个应该和函数一样是一个值传递还是参数 ...

  6. java 并发多线程 锁的分类概念介绍 多线程下篇(二)

    接下来对锁的概念再次进行深入的介绍 之前反复的提到锁,通常的理解就是,锁---互斥---同步---阻塞 其实这是常用的独占锁(排它锁)的概念,也是一种简单粗暴的解决方案 抗战电影中,经常出现为了阻止日 ...

  7. .NET Core:多样的宿主

     .NET Core 可以以以下方式作为宿主运行: IIS 控制台 Windows服务 运行启动代码:         public static void Main(string[] args)   ...

  8. React create-react-app Build fails after eject: Cannot find module '@babel/plugin-transform-react-jsx'

    运行 npm run eject 出现报错 Build fails after eject: Cannot find module '@babel/plugin-transform-react-jsx ...

  9. java基础(一):谈谈java内存管理与垃圾回收机制

    看了很多java内存管理的文章或者博客,写的要么笼统,要么划分的不正确,且很多文章都千篇一律.例如部分地方将jvm笼统的分为堆.栈.程序计数器,这么分太过于笼统,无法清晰的阐述java的内存管理模型: ...

  10. 项目实战工具类(二):ZipUtils(压缩/解压缩文件相关)

    import android.content.Context; import android.util.Log; import java.io.File; import java.io.FileInp ...