什么是retrofit?
-
首先看下retrofit的官网
A type-safe HTTP client for Android and Java
retrofit 基于okhttp封装的网络请求框架, 其网络请求的底层使用实际是使用okHttp来完成,retrofit 仅负责网络请求接口的封装。
使用retrofit 可以使http调用请求如同本地调用一般优雅丝滑。
spring boot使用retrofit快速开发更优雅的http请求
-
首先新建一个springboot工程,这里推荐一个创建java工程的网站:
勾选需要的配置,选择获取代码,可以直接下载,也可以使用git获取
-
引入retrofit依赖
<dependency> <groupId>com.github.lianjiatech</groupId> <artifactId>retrofit-spring-boot-starter</artifactId> <version>2.0.2</version> </dependency> <dependency> <groupId>com.squareup.retrofit2</groupId> <artifactId>converter-gson</artifactId> <version>2.0.2</version> </dependency> -
编写测试请求接口
/** * retrofit调用接口 * * @return */ @GetMapping("/retrofit") @ResponseBody public String retrofit() { return "retrofit"; } -
编写retrofit接口
package com.example.demo.api; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.GET; /** * @Description: * @Author: yezi * @Date: 2021/3/12 15:00 */ public interface DemoApiService { @GET("/retrofit") Call<ResponseBody> demoHttp(); } -
编写retrofit配置类
package com.example.demo.api; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; /** * @Description: * @Author: yezi * @Date: 2021/3/12 14:31 */ @Configuration public class ApiConfig { @Bean public DemoApiService demoApiService(){ Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://127.0.0.1:8080") .addConverterFactory(GsonConverterFactory.create()) .build(); DemoApiService demoApiService = retrofit.create(DemoApiService.class); return demoApiService; } } -
编写测试请求
package com.example.demo; import com.example.demo.api.DemoApiService; import okhttp3.ResponseBody; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import retrofit2.Call; import java.io.IOException; @SpringBootTest class DemoApplicationTests { @Autowired DemoApiService demoApiService; @Test void contextLoads() throws IOException { Call<ResponseBody> responseBodyCall = demoApiService.demoHttp(); String string = responseBodyCall.execute().body().string(); System.out.println(string); } } -
测试结果
以上为java使用retrofit调用http请求,是不是如同调用本地方法一般~~另外还有Feign也可以实现类似的操作,有兴趣的朋友可以自行了解~