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: \n");
while ((output = responseBuffer.readLine()) != null) {
System.out.println(output);
}
httpConnection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73

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<NameValuePair> nvps = new ArrayList<NameValuePair>();
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;
}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103

4.Spring的RestTemplate

springmvc.xml增加

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

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<User> 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<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("id", "啊啊啊");
postParameters.add("name", "部版本");
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
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; }
}

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

  1. Java调用RestFul接口

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

  2. JAVA写JSON的三种方法,java对象转json数据

    JAVA写JSON的三种方法,java对象转json数据 转自:http://www.xdx97.com/#/single?bid=5afe2ff9-8cd1-67cf-e7bc-437b74c07a ...

  3. 数组k平移三种方法(java)

    上代码,本文用了三种方法实现,时间复杂度不一样,空间复杂度都是o(1): public class ArrayKMove { /** * 问题:数组的向左k平移,k小于数组长度 * @param ar ...

  4. java调用restful接口的方法

    Restful接口的调用,前端一般使用ajax调用,后端可以使用的方法如下: 1.HttpURLConnection实现 2.HttpClient实现 3.Spring的RestTemplate

  5. Java方法通过RestTemplate调用restful接口

    背景:项目A需要在代码内部调用项目B的一个restful接口,该接口是POST方式,header中 Authorization为自定义内容,主要传输的内容封装在body中,所以使用到了RestTemp ...

  6. Top k问题的讨论(三种方法的java实现及适用范围)

    在很多的笔试和面试中,喜欢考察Top K.下面从自身的经验给出三种实现方式及实用范围. 合并法 这种方法适用于几个数组有序的情况,来求Top k.时间复杂度为O(k*m).(m:为数组的个数).具体实 ...

  7. Java 调用Restful API接口的几种方式--HTTPS

    摘要:最近有一个需求,为客户提供一些Restful API 接口,QA使用postman进行测试,但是postman的测试接口与java调用的相似但并不相同,于是想自己写一个程序去测试Restful ...

  8. Java实现ping功能的三种方法及Linux的区分

    前大半部份转自:https://blog.csdn.net/futudeniaodan/article/details/52317650 检测设备的运行状态,有的是使用ping的方式来检测的.所以需要 ...

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

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

随机推荐

  1. 选择 Python3.6 还是 Python 3.7

    转自:白月黑羽在线教程:http://www.python3.vip/doc/blog/python/home/ 选择 Python3.6 还是 Python 3.7 Python 3.7 已经发布了 ...

  2. 分布式锁的两种实现方式(基于redis和基于zookeeper)

    先来说说什么是分布式锁,简单来说,分布式锁就是在分布式并发场景中,能够实现多节点的代码同步的一种机制.从实现角度来看,主要有两种方式:基于redis的方式和基于zookeeper的方式,下面分别简单介 ...

  3. Go http handler 中间件

    在http的handler处理中加上中间件,可以进行过滤.记录日志.统计和统一返回结果 package main import ( "fmt" "net/http&quo ...

  4. android app启动过程

    Native进程的运行过程 一般程序的启动步骤,可以用下图描述.程序由内核加载分析,使用linker链接需要的共享库,然后从c运行库的入口开始执行. 通常,native进程是由shell或者init启 ...

  5. 团队作业6——展示博客(alpha阶段)

    Deadline: 2018-5-9 10:00PM,以提交至班级博客时间为准. 5.10周四实验课将进行alpha阶段项目复审,请在5.10之前,根据以下要求,完成alpha版本的展示,并以此作为参 ...

  6. 解决:git使用git push 命令跳出remote: Permission to A denied to B的问题

    开始git上传项目,不料,在git push这一步骤发生了错误? remote: Permission to qwe2193066947/firstRepository.git denied to m ...

  7. 阿里巴巴java手册示例

    package com.led.daorumysql; /** * @Description:alibaba java development manual * @author 86157 * */ ...

  8. 分布式理论(一) —— CAP 定理

    目录: 什么是 CAP 定理 为什么只能 3 选 2 能不能解决 3 选 2 的问题 引用 1. 什么是 CAP 定理 2000 年的时候,Eric Brewer 教授提出了 CAP 猜想,2年后,被 ...

  9. .17-浅析webpack源码之compile流程-入口函数run

    本节流程如图: 现在正式进入打包流程,起步方法为run: Compiler.prototype.run = (callback) => { const startTime = Date.now( ...

  10. Spring学习之路-SpringBoot简单入门

    简单讲SpringBoot是对spring和springMVC的二次封装和整合,新添加了一些注解和功能,不算是一个新框架. 学习来源是官方文档,虽然很详细,但是太墨迹了… 地址:https://doc ...