Introduction
Retrofit is a type-safe HTTP client tool suitable for Android
and Java
. It already has 39k
on Github. Star. Its biggest feature is that it supports initiating HTTP requests through the interface, similar to the way we use Feign to call the microservice interface.
SpringBoot is the most widely used Java development framework, but Retrofit officially does not provide a dedicated Starter. So an old man developed retrofit-spring-boot-starter
, which realized the rapid integration of Retrofit and SpringBoot framework, and supported many functional enhancements, greatly simplifying development. Today we will use this third-party Starter to operate Retrofit.
Using
It is very simple to use Retrofit in SpringBoot. Let’s experience it below.
Dependency Integration
With the support of third-party Starter, integrating Retrofit only requires one step, just add the following dependencies.
<!--Retrofit依赖--> <dependency> <groupId>com.github.lianjiatech</groupId> <artifactId>retrofit-spring-boot-starter</artifactId> <version>2.2.18</version> </dependency>
Basic use
Let’s take the interface in mall-tiny-swagger
as an example to experience the basic use of Retrofit.
First we prepare a service to facilitate remote calls. We use the previous mall-tiny-swagger
Demo. Open Swagger and take a look. There is a login interface and login authentication required. Product brand CRUD interface,
Let’s try calling the login interface first, and configure mall-tiny- in
application.yml The service address of swagger
;
remote: baseUrl: http://localhost:8088/
declares a Retrofit client through @RetrofitClient
. Since the login interface is called through the POST form, @POST is used here
and @FormUrlEncoded
annotations;
/** * 定义Http接口,用于调用远程的UmsAdmin服务 * Created by macro on 2022/1/19. */ @RetrofitClient(baseUrl = "${remote.baseUrl}") public interface UmsAdminApi { @FormUrlEncoded @POST("admin/login") CommonResult<LoginInfo> login(@Field("username") String username, @Field("password") String password); }
If you don’t quite understand what these annotations are for, you can basically understand them by looking at the table below. For more specific information, you can refer to the Retrofit official website Document;
Next, inject UmsAdminApi
into the Controller and then call it;
/** * Retrofit测试接口 * Created by macro on 2022/1/19. */ @Api(tags = "RetrofitController", description = "Retrofit测试接口") @RestController @RequestMapping("/retrofit") public class RetrofitController { @Autowired private UmsAdminApi umsAdminApi; @Autowired private TokenHolder tokenHolder; @ApiOperation(value = "调用远程登录接口获取token") @PostMapping(value = "/admin/login") public CommonResult<LoginInfo> login(@RequestParam String username, @RequestParam String password) { CommonResult<LoginInfo> result = umsAdminApi.login(username, password); LoginInfo loginInfo = result.getData(); if (result.getData() != null) { tokenHolder.putToken(loginInfo.getTokenHead() + " " + loginInfo.getToken()); } return result; } }
requires login to facilitate subsequent calls. For the authentication interface, I created the TokenHolder
class and stored the token in the Session;
/** * 登录token存储(在Session中) * Created by macro on 2022/1/19. */ @Component public class TokenHolder { /** * 添加token */ public void putToken(String token) { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest(); request.getSession().setAttribute("token", token); } /** * 获取token */ public String getToken() { RequestAttributes ra = RequestContextHolder.getRequestAttributes(); HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest(); Object token = request.getSession().getAttribute("token"); if(token!=null){ return (String) token; } return null; } }
Next, test it through Swagger, and you can get the token returned by the remote service by calling the interface. , access address: http://localhost:8086/swagger-ui/
Annotation interceptor
Product brand management interface, login authentication needs to be added The header can be accessed normally, and we can use the annotation interceptor in Retrofit to achieve this.
First create an annotation interceptor TokenInterceptor
Inherit BasePathMatchInterceptor
, and then add Authorization
to the request in the doIntercept
method header;
/** * 给请求添加登录Token头的拦截器 * Created by macro on 2022/1/19. */ @Component public class TokenInterceptor extends BasePathMatchInterceptor { @Autowired private TokenHolder tokenHolder; @Override protected Response doIntercept(Chain chain) throws IOException { Request request = chain.request(); if (tokenHolder.getToken() != null) { request = request.newBuilder() .header("Authorization", tokenHolder.getToken()) .build(); } return chain.proceed(request); } }
Create a client that calls the brand management interfacePmsBrandApi
, and use the @Intercept
annotation to configure the interceptor and interception path;
/** * 定义Http接口,用于调用远程的PmsBrand服务 * Created by macro on 2022/1/19. */ @RetrofitClient(baseUrl = "${remote.baseUrl}") @Intercept(handler = TokenInterceptor.class, include = "/brand/**") public interface PmsBrandApi { @GET("brand/list") CommonResult<CommonPage<PmsBrand>> list(@Query("pageNum") Integer pageNum, @Query("pageSize") Integer pageSize); @GET("brand/{id}") CommonResult<PmsBrand> detail(@Path("id") Long id); @POST("brand/create") CommonResult create(@Body PmsBrand pmsBrand); @POST("brand/update/{id}") CommonResult update(@Path("id") Long id, @Body PmsBrand pmsBrand); @GET("brand/delete/{id}") CommonResult delete(@Path("id") Long id); }
then Inject the PmsBrandApi
instance into the Controller and add a method to call the remote service;
/** * Retrofit测试接口 * Created by macro on 2022/1/19. */ @Api(tags = "RetrofitController", description = "Retrofit测试接口") @RestController @RequestMapping("/retrofit") public class RetrofitController { @Autowired private PmsBrandApi pmsBrandApi; @ApiOperation("调用远程接口分页查询品牌列表") @GetMapping(value = "/brand/list") public CommonResult<CommonPage<PmsBrand>> listBrand(@RequestParam(value = "pageNum", defaultValue = "1") @ApiParam("页码") Integer pageNum, @RequestParam(value = "pageSize", defaultValue = "3") @ApiParam("每页数量") Integer pageSize) { return pmsBrandApi.list(pageNum, pageSize); } @ApiOperation("调用远程接口获取指定id的品牌详情") @GetMapping(value = "/brand/{id}") public CommonResult<PmsBrand> brand(@PathVariable("id") Long id) { return pmsBrandApi.detail(id); } @ApiOperation("调用远程接口添加品牌") @PostMapping(value = "/brand/create") public CommonResult createBrand(@RequestBody PmsBrand pmsBrand) { return pmsBrandApi.create(pmsBrand); } @ApiOperation("调用远程接口更新指定id品牌信息") @PostMapping(value = "/brand/update/{id}") public CommonResult updateBrand(@PathVariable("id") Long id, @RequestBody PmsBrand pmsBrand) { return pmsBrandApi.update(id,pmsBrand); } @ApiOperation("调用远程接口删除指定id的品牌") @GetMapping(value = "/delete/{id}") public CommonResult deleteBrand(@PathVariable("id") Long id) { return pmsBrandApi.delete(id); } }
Call the interface in Swagger for testing and find that it can be called successfully.
Global interceptor
If you want to add a request header to all requests, you can use the global interceptor.
Create the SourceInterceptor
class to inherit the BaseGlobalInterceptor
interface, and then add the source
request header to the Header.
/** * 全局拦截器,给请求添加source头 * Created by macro on 2022/1/19. */ @Component public class SourceInterceptor extends BaseGlobalInterceptor { @Override protected Response doIntercept(Chain chain) throws IOException { Request request = chain.request(); Request newReq = request.newBuilder() .addHeader("source", "retrofit") .build(); return chain.proceed(newReq); } }
Configuration
Retrofit has many configurations. Let’s talk about the three most commonly used configurations: log printing, global timeout and global request retry.
Log printing Under the default configuration, Retrofit uses the basic
log strategy, and the printed log is very simple;
We can The retrofit.global-log-strategy
attribute in application.yml
is modified to body
to print the most complete log;
retrofit: # 日志打印配置 log: # 启用日志打印 enable: true # 日志打印拦截器 logging-interceptor: com.github.lianjiatech.retrofit.spring.boot.interceptor.DefaultLoggingInterceptor # 全局日志打印级别 global-log-level: info # 全局日志打印策略 global-log-strategy: body
modifies log printing After setting the policy, the log information is more comprehensive;
- NONE: Do not print logs;
- BASIC: Only print log request records;
HEADERS:打印日志请求记录、请求和响应头信息;
BODY:打印日志请求记录、请求和响应头信息、请求和响应体信息。
全局超时时间
有时候我们需要修改一下Retrofit的请求超时时间,可以通过如下配置实现。
retrofit: # 全局连接超时时间 global-connect-timeout-ms: 3000 # 全局读取超时时间 global-read-timeout-ms: 3000 # 全局写入超时时间 global-write-timeout-ms: 35000 # 全局完整调用超时时间 global-call-timeout-ms: 0
全局请求重试
retrofit-spring-boot-starter
支持请求重试,可以通过如下配置实现。
retrofit: # 重试配置 retry: # 是否启用全局重试 enable-global-retry: true # 全局重试间隔时间 global-interval-ms: 100 # 全局最大重试次数 global-max-retries: 2 # 全局重试规则 global-retry-rules: - response_status_not_2xx - occur_exception # 重试拦截器 retry-interceptor: com.github.lianjiatech.retrofit.spring.boot.retry.DefaultRetryInterceptor
重试规则global-retry-rules
支持如下三种配置。
RESPONSE_STATUS_NOT_2XX:响应状态码不是2xx时执行重试;
OCCUR_IO_EXCEPTION:发生IO异常时执行重试;
OCCUR_EXCEPTION:发生任意异常时执行重试。
The above is the detailed content of How to use the HTTP client tool Retrofit in SpringBoot. For more information, please follow other related articles on the PHP Chinese website!

Springboot内置tomcat禁止不安全HTTP方法1、在tomcat的web.xml中可以配置如下内容让tomcat禁止不安全的HTTP方法/*PUTDELETEHEADOPTIONSTRACEBASIC2、Springboot使用内置tomcat没有web.xml配置文件,可以通过以下配置进行,简单来说就是要注入到Spring容器中@ConfigurationpublicclassTomcatConfig{@BeanpublicEmbeddedServletContainerFacto

1.HttpURLConnection使用JDK原生提供的net,无需其他jar包,代码如下:importcom.alibaba.fastjson.JSON;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.net.HttpURLConnection;

一、前言#ssl写在443端口后面。这样http和https的链接都可以用listen443sslhttp2default_server;server_namechat.chengxinsong.cn;#hsts的合理使用,max-age表明hsts在浏览器中的缓存时间,includesubdomainscam参数指定应该在所有子域上启用hsts,preload参数表示预加载,通过strict-transport-security:max-age=0将缓存设置为0可以撤销hstsadd_head

随着互联网的不断发展和改善,Web服务器在速度和性能上的需求也越来越高。为了满足这样的需求,Nginx已经成功地掌握了HTTP2协议并将其融入其服务器的性能中。HTTP2协议要比早期的HTTP协议更加高效,但同时也存在着特定的安全问题。本文将为您详细介绍如何进行Nginx的HTTP2协议优化和安全设置。一、Nginx的HTTP2协议优化1.启用HTTP2在N

httpkeepalive在http早期,每个http请求都要求打开一个tpcsocket连接,并且使用一次之后就断开这个tcp连接。使用keep-alive可以改善这种状态,即在一次tcp连接中可以持续发送多份数据而不会断开连接。通过使用keep-alive机制,可以减少tcp连接建立次数,也意味着可以减少time_wait状态连接,以此提高性能和提高httpd服务器的吞吐率(更少的tcp连接意味着更少的系统内核调用,socket的accept()和close()调用)。但是,keep-ali

一、urllib概述:urllib是Python中请求url连接的官方标准库,就是你安装了python,这个库就已经可以直接使用了,基本上涵盖了基础的网络请求功能。在Python2中主要为urllib和urllib2,在Python3中整合成了urllib。Python3.x中将urllib2合并到了urllib,之后此包分成了以下四个模块:urllib.request:它是最基本的http请求模块,用来模拟发送请求urllib.error:异常处理模块,如果出现错误可以捕获这些异常urllib

被动检查对于被动健康检查,nginx和nginxplus会在事件发生时对其进行监控,并尝试恢复失败的连接。如果仍然无法恢复正常,nginx开源版和nginxplus会将服务器标记为不可用,并暂时停止向其发送请求,直到它再次标记为活动状态。上游服务器标记为不可用的条件是为每个上游服务器定义的,其中包含块中server指令的参数upstream:fail_timeout-设置服务器标记为不可用时必须进行多次失败尝试的时间,以及服务器标记为不可用的时间(默认为10秒)。max_fails-设置在fai

一、概述在实际开发过程中,我们经常需要调用对方提供的接口或测试自己写的接口是否合适。很多项目都会封装规定好本身项目的接口规范,所以大多数需要去调用对方提供的接口或第三方接口(短信、天气等)。在Java项目中调用第三方接口的方式有:1、通过JDK网络类Java.net.HttpURLConnection;2、通过common封装好的HttpClient;3、通过Apache封装好的CloseableHttpClient;4、通过SpringBoot-RestTemplate;二、Java调用第三方


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

Dreamweaver Mac version
Visual web development tools