Retrofit是Java开发的一种轻量级Http请求组件,可以做到类似于接口调用一样的方式进行http调用。废话不多说,直接上代码
1、maven依赖
<dependency>
<groupId>com.github.lianjiatech</groupId>
<artifactId>retrofit-spring-boot-starter</artifactId>
<version>2.0.2</version>
</dependency>
这里使用2.0.2版本的
2、retrofit接口的声明
import com.github.lianjiatech.retrofit.spring.boot.annotation.Intercept;
import com.github.lianjiatech.retrofit.spring.boot.annotation.RetrofitClient;
import com.demo.web.retrofit.RetrofitInterceptor;
import com.demo.web.retrofit.RetrofitResult;
import retrofit2.http.GET;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import java.util.Map;
/**
*/
@RetrofitClient(baseUrl = "${retrofit.server.url}",connectTimeoutMs=1000 * 60)
@Intercept(handler = RetrofitInterceptor.class)
public interface DocRetrofitService {
/**
* 文章博客查询分页
*/
@GET("/doc/word/blogList")
public RetrofitResult queryList(@QueryMap Map<String,Object> data);
@RetrofitClient定义接口的域名或者地址,此处可以使用spring的yml配置。
@Intercept 拦截器,可以自定义一个接口拦截器
这里需要注意下 RetrofitClient的baseUrl不用包含路径,否则组件不会识别,组件会自动将baseUrl和方法上的/doc/word/blogList路径拼接在一起。
接口的返回值,可以自己定义,组件会自动序列化完成返回,不过为了统一,最好使用统一的格式,为了拦截器可以统一判错
比如下面这个
import com.github.lianjiatech.retrofit.spring.boot.interceptor.BasePathMatchInterceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
@Component
public class RetrofitInterceptor extends BasePathMatchInterceptor {
@Override
protected Response doIntercept(Chain chain) throws IOException {
Request req = chain.request();
Request newReq = req.newBuilder()
.url(req.url())
.header("token","111111")
.build();
Response response = chain.proceed(newReq);
ResponseBody res = response.body();
Assert.isTrue(res != null ,"execute url "+req.url()+" error, because return body is null");
String result = getResponseStr(res);
RetrofitResult<Object> obj = null;
try{
obj = JsonHelper.parseJson(result,RetrofitResult.class,Object.class);
}catch (Exception e){
throw new RuntimeException("execute "+req.url()+" error!"+e.getMessage());
}
if(obj.getCode() == null){
throw new RuntimeException("返回数据错误,缺少code");
}
Assert.isTrue(obj.getCode() == 0 ,obj.getMsg());
return response;
}
private String getResponseStr(ResponseBody responseBody) throws IOException {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // request the entire body.
Buffer buffer = source.buffer();
return buffer.clone().readString(StandardCharsets.UTF_8);
}
}
spring application.yml配置
retrofit:
server:
url: http://www.test.com