Spring-Boot 访问外部接口的几种方案总结
一、简介
在Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求,针对这一需求目前存在着三种解决方案,下面将对这三种方案进行整理和说明。
二、Spring-Boot项目中访问外部接口
2.1 方案一 采用原生的Http请求
在代码中采用原生的http请求,代码参考如下:
@RequestMapping("/doPostGetJson")
public String doPostGetJson() throws ParseException {
//此处将要发送的数据转换为json格式字符串
String jsonText = "{id:1}";
JSONObject json = (JSONObject) JSONObject.parse(jsonText);
JSONObject sr = this.doPost(json);
System.out.println("返回参数:" + sr);
return sr.toString();
} public static JSONObject doPost(JSONObject date) {
HttpClient client = HttpClients.createDefault();
// 要调用的接口方法
String url = "http://192.168.1.101:8080/getJson";
HttpPost post = new HttpPost(url);
JSONObject jsonObject = null;
try {
StringEntity s = new StringEntity(date.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");
post.setEntity(s);
post.addHeader("content-type", "text/xml");
HttpResponse res = client.execute(post);
String response1 = EntityUtils.toString(res.getEntity());
System.out.println(response1);
if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
String result = EntityUtils.toString(res.getEntity());// 返回json格式:
jsonObject = JSONObject.parseObject(result);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return jsonObject;
}
2.2 方案二 采用Feign进行消费
(1)在maven项目中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-feign</artifactId>
<version>1.2.2.RELEASE</version>
</dependency>
(2)编写接口,放置在service层
@FeignClient(url = "${decisionEngine.url}",name="engine")
public interface DecisionEngineService {
@RequestMapping(value="/decision/person",method= RequestMethod.POST)
public JSONObject getEngineMesasge(@RequestParam("uid") String uid,@RequestParam("productCode") String productCode); }
这里的decisionEngine.url 是配置在properties中的 是ip地址和端口号
decisionEngine.url=http://10.2.1.148:3333
/decision/person 是接口名字
(3)在Java的启动类上加上@EnableFeignClients
@EnableFeignClients //参见此处
@EnableDiscoveryClient
@SpringBootApplication
@EnableResourceServer
public class Application implements CommandLineRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
@Autowired
private AppMetricsExporter appMetricsExporter; @Autowired
private AddMonitorUnitService addMonitorUnitService; public static void main(String[] args) {
new SpringApplicationBuilder(Application.class).web(true).run(args);
}
}
(4)在代码中调用接口即可
@Autowired
private DecisionEngineService decisionEngineService ;
decisionEngineService.getEngineMesasge("uid" , "productCode");
2.3、方案三 采用RestTemplate方法
在Spring-Boot开发中,RestTemplate同样提供了对外访问的接口API,这里主要介绍Get和Post方法的使用。Get请求提供了两种方式的接口getForObject 和 getForEntity,getForEntity提供如下三种方法的实现。
(1) Get请求之——getForEntity(Stringurl,Class responseType,Object…urlVariables)
该方法提供了三个参数,其中url为请求的地址,responseType为请求响应body的包装类型,urlVariables为url中的参数绑定,该方法的参考调用如下:
//http://USER-SERVICE/user?name={1}
getForEntity("http://USER-SERVICE/user?name={1}",String.class,"didi")
(2)Get请求之——getForEntity(String url,Class responseType,Map urlVariables)
该方法提供的参数中urlVariables的参数类型使用了Map类型,因此在使用该方法进行参数绑定时需要在占位符中指定Map中参数的key值,该方法的参考调用如下:
// http://USER-SERVICE/user?name={name)
RestTemplate restTemplate=new RestTemplate();
Map<String,String> params=new HashMap<>();
params.put("name","dada"); //
ResponseEntity<String> responseEntity=restTemplate.getForEntity("http://USERSERVICE/user?name={name}",String.class,params);
(3)Get请求之——getForEntity(URI url,Class responseType)
该方法使用URI对象来替代之前的url和urlVariables参数来指定访问地址和参数绑定。URI是JDK java.net包下的一个类,表示一个统一资源标识符(Uniform Resource Identifier)引用。参考如下:
RestTemplate restTemplate=new RestTemplate();
UriComponents uriComponents=UriComponentsBuilder.fromUriString(
"http://USER-SERVICE/user?name={name}")
.build()
.expand("dodo")
.encode();
URI uri=uriComponents.toUri();
ResponseEntity<String> responseEntity=restTemplate.getForEntity(uri,String.class).getBody();
(4)Get请求之——getForObject
getForObject方法可以理解为对getForEntity的进一步封装,它通过HttpMessageConverterExtractor对HTTP的请求响应体body内容进行对象转换,实现请求直接返回包装好的对象内容。getForObject方法有如下:
getForObject(String url,Class responseType,Object...urlVariables)
getForObject(String url,Class responseType,Map urlVariables)
getForObject(URI url,Class responseType)
(5)Post请求提供有三种方法,postForEntity、postForObject和postForLocation。其中每种方法都存在三种方法,postForEntity方法使用如下:
RestTemplate restTemplate=new RestTemplate();
User user=newUser("didi",30);
ResponseEntity<String> responseEntity=restTemplate.postForEntity("http://USER-SERVICE/user",user,String.class); //提交的body内容为user对象,请求的返回的body类型为String
String body=responseEntity.getBody();
(6)postForEntity存在如下三种方法的重载
postForEntity(String url,Object request,Class responseType,Object... uriVariables)
postForEntity(String url,Object request,Class responseType,Map uriVariables)
postForEntity(URI url,Object request,Class responseType)
postForEntity中的其它参数和getForEntity的参数大体相同在此不做介绍。
Spring-Boot 访问外部接口的几种方案总结的更多相关文章
- Spring Boot - 访问外部接口最全总结
Spring Boot - 访问外部接口 在Spring-Boot项目开发中,存在着本模块的代码需要访问外面模块接口,或外部url链接的需求, 比如调用外部的地图API或者天气API. Spring ...
- Spring Boot 配置文件密码加密两种方案
Spring Boot 配置文件密码加密两种方案 jasypt 加解密 jasypt 是一个简单易用的加解密Java库,可以快速集成到 Spring 项目中.可以快速集成到 Spring Boot 项 ...
- Spring Boot 整合 Shiro ,两种方式全总结!
在 Spring Boot 中做权限管理,一般来说,主流的方案是 Spring Security ,但是,仅仅从技术角度来说,也可以使用 Shiro. 今天松哥就来和大家聊聊 Spring Boot ...
- spring boot访问数据库
1. Spring JAP 基本使用说明: Spring boot 访问数据库基本上都是通过Spring JPA封装的Bean作为API的,Spring JPA 将访问数据库通过封装,只要你的类实现了 ...
- 使用spring boot访问mongodb数据库
一. spring boot中传参的方法 1.自动化配置 spring Boot 对于开发人员最大的好处在于可以对 Spring 应用进行自动配置.Spring Boot 会根据应用中声明的第三方依赖 ...
- Spring Boot配置过滤器的两种方式
过滤器(Filter)是Servlet中常用的技术,可以实现用户在访问某个目标资源之前,对访问的请求和响应进行拦截,常用的场景有登录校验.权限控制.敏感词过滤等,下面介绍下Spring Boot配置过 ...
- Spring Boot 注册 Servlet 的三种方法,真是太有用了!
本文栈长教你如何在 Spring Boot 注册 Servlet.Filter.Listener. 你所需具备的基础 什么是 Spring Boot? Spring Boot 核心配置文件详解 Spr ...
- Spring Boot应用启动的三种方式
Spring Boot应用HelloWorld的三种启动方式: 项目的创建可以在http://start.spring.io/网站中进行项目的创建. 首先项目结构: 1. 通过main方法的形式启动 ...
- Spring Boot 邮件发送的 5 种姿势!
邮件发送其实是一个非常常见的需求,用户注册,找回密码等地方,都会用到,使用 JavaSE 代码发送邮件,步骤还是挺繁琐的,Spring Boot 中对于邮件发送,提供了相关的自动化配置类,使得邮件发送 ...
随机推荐
- hdu 1671 Phone List 统计前缀次数
Phone List Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total ...
- Redis的安装并配置快捷启动
Redis 安装 1.下载 wget http://download.redis.io/releases/redis-5.0.5.tar.gz 2.解压 tar -zxvf redis-5.0.5.t ...
- 【剑指Offer】面试题24. 反转链表
题目 定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点. 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3 ...
- 找《飘》 中最常用的N个单词。
找<飘> 中最常用的N个单词. 1,题目:输出单个文件(<飘> 英文版)中的前 N 个最常出现的英语单词,并将结果输入到文本文件中. 2,设计思路: 1),按行依次读取文件并按 ...
- C++ 管道
// PipeServer.cpp : Defines the entry point for the console application. // #include "stdafx.h& ...
- datetime使用
通过当前日期,获取最近第一个周五.第二个周五.每季度末最后一个周五 def get_current_week(self, symbol: str, start_date: datetime): i ...
- 【转】TransactionScope事务处理方法介绍及.NET Core中的注意事项
什么是TransactionScope呢? TransactionScope作为System.Transactions的一部分被引入到.NET 2.0.同时SqlClient for .NET Cor ...
- centos 制作指定需求命令的YUM源
场景: 没有YUM源,但是需要安装一些用到的命令,如vim,telnet等少量命令,不想YUM源太大,满足需求即可.于是制作一个仅需要满足要求的yum源 步骤一: 联网环境下安装createreo命令 ...
- Android进阶——多线程系列之Semaphore、CyclicBarrier、CountDownLatch
今天向大家介绍的是多线程开发中的一些辅助类,他们的作用无非就是帮助我们让多个线程按照我们想要的执行顺序来执行.如果我们按照文字来理解Semaphore.CyclicBarrier.CountDownL ...
- 利用libpcap抓取数据包
转载自:http://blog.csdn.net/tennysonsky/article/details/44811899 概述 libpcap是一个网络数据包捕获函数库,tcpdump就是以libp ...