一、背景
因為業務關系,要和許多不同第三方公司進行對接。這些服務商都提供基於http的api。但是每家公司提供api具體細節差別很大。有的基於RESTFUL規范,有的基於傳統的http規范;有的需要再header里放置簽名,有的需要SSL的雙向認證,有的只需要SSL的單向認證;有的以JSON 方式進行序列化,有的以XML方式進行序列化。類似於這樣細節的差別太多了。
於是了解到了Forest
Forest是什么?
Forest是一個高層的、極簡的輕量級 HTTP調用API框架,讓Java發送HTTP/HTTPS請求不再難。它比OkHttp和HttpClient更高層,比Feign更輕量,是封裝調用第三方restful api client接口的好幫手。
相比於直接使用Httpclient我們不再寫一大堆重復的代碼了,而是像調用本地方法一樣去發送HTTP請求。
二、SpringBoot整合Forest實現調用第三方接口
1、pom.xml
中引入依賴
<!-- Forest --> <dependency> <groupId>com.dtflys.forest</groupId> <artifactId>spring-boot-starter-forest</artifactId> <version>1.4.0</version> </dependency>
2、application.yml
中相關配置
# ========================== ↓↓↓↓↓↓ forest配置 ↓↓↓↓↓↓ ========================== forest: bean-id: config0 # 在spring上下文中bean的id, 默認值為forestConfiguration backend: okhttp3 # 后端HTTP API: okhttp3 【支持`okhttp3`/`httpclient`】 max-connections: 1000 # 連接池最大連接數,默認值為500 max-route-connections: 500 # 每個路由的最大連接數,默認值為500 timeout: 3000 # 請求超時時間,單位為毫秒, 默認值為3000 connect-timeout: 3000 # 連接超時時間,單位為毫秒, 默認值為2000 retry-count: 0 # 請求失敗后重試次數,默認為0次不重試 ssl-protocol: SSLv3 # 單向驗證的HTTPS的默認SSL協議,默認為SSLv3 logEnabled: true # 打開或關閉日志,默認為true
3、配置掃描接口
在啟動類上加上@ForestScan
注解,並在basePackages
屬性中填寫遠程接口所在的包名
// forest掃描遠程接口所在的包名 @ForestScan(basePackages = "com.wanli.demo.client") @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
4、構建請求接口
public interface MyClient { /** * 本地測試接口 */ @Get(url = "http://127.0.0.1:80/demo/index") String index(); @Get(url = "http://127.0.0.1:80/demo/hello?msg=${msg}") String hello(@DataVariable("msg") String msg); /** * 高德地圖API */ @Get(url = "http://ditu.amap.com/service/regeo?longitude=${longitude}&latitude=${latitude}") Map getLocation(@DataVariable("longitude") String longitude, @DataVariable("latitude") String latitude); }
5、測試
@Slf4j @RunWith(SpringRunner.class) @SpringBootTest public class DemoTest { @Autowired private MyClient myClient; @Test public void testForest() throws Exception { // 調用接口 String index = myClient.index(); log.info("index: 【{}】", index); String hello = myClient.hello("測試..."); log.info("hello: 【{}】", hello); Map location = myClient.getLocation("121.475078", "31.223577"); log.info("location: 【{}】", location.toString()); System.out.println(JSON.toJSONString(location)); } }