Home > Java > javaTutorial > body text

How to use the HTTP client tool Retrofit in SpringBoot

王林
Release: 2023-05-12 11:55:20
forward
987 people have browsed it

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.

How to use the HTTP client tool Retrofit in SpringBoot

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.

How to use the HTTP client tool Retrofit in SpringBoot

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>
Copy after login

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,

How to use the HTTP client tool Retrofit in SpringBoot

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/
Copy after login

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);
}
Copy after login

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;

How to use the HTTP client tool Retrofit in SpringBoot

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;
    }
}
Copy after login

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;
    }
}
Copy after login

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/

How to use the HTTP client tool Retrofit in SpringBoot

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 TokenInterceptorInherit 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);
    }
}
Copy after login

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);
}
Copy after login

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);
    }
}
Copy after login

Call the interface in Swagger for testing and find that it can be called successfully.

How to use the HTTP client tool Retrofit in SpringBoot

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);
    }
}
Copy after login

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;

How to use the HTTP client tool Retrofit in SpringBoot

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
Copy after login

modifies log printing After setting the policy, the log information is more comprehensive;

How to use the HTTP client tool Retrofit in SpringBoot

##Retrofit supports four log printing strategies;

  • 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
Copy after login

全局请求重试

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
Copy after login

重试规则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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template