研究了Retrofit的基本使用,用法如下(Retrofit在Android和Java程序中都可以运行,本次以JAVA项目来实践):
1.引入jar包
在默认情况下Retrofit只支持将HTTP的响应体转换换为ResponseBody
,需要一个Converter让Retrofit为我们提供用于将ResponseBody
转换为我们想要的类型,所以引入了converter-gson的jar包
<dependencies>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>retrofit</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.squareup.retrofit2</groupId>
<artifactId>converter-gson</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
2.创建Retrofit实例
Retrofit 2 在文档上要求baseUrl必须以 /(斜线) 结尾
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(serverPath)
.addConverterFactory(GsonConverterFactory.create())
.build();
3.定义接口,接口中为对应的REST请求
3.1:通过@Get,@Post来标注请求方式,value为相对于baseUrl的相对路径
3.2: Post的请求参数被@Body
注解的的对象将会被Gson转换成RequestBody发送到服务器
3.3:url的路径带参通过@Path和@Query实现。
3.4:@Header来携带请求头的的参数
@POST(URL_Login)
Call<LoginResponseModel> login(@Body LoginRequestModel model);
@GET(URL_Route)
Call<ResponseBody> dataSyncRouteCustomerInfo(@Path("routeNo")String routeNo,@Header(token)String token );
@GET(URL_Activity)
Call<ResponseBody> getCustomerActivityList(@Path("routeNo")String routeNo,@Query("outletNo")String outletNo,@Header(token)String token );
4.通过Retrofit创建接口对象,调用方法
4.1 创建对象:
RestService service = retrofit.create(RestService.class);
4.2 调用对应方法
LoginRequestModel model = new LoginRequestModel();
model.employeeNo = username;
model.password = password;
Call<LoginResponseModel> call = service.login(model);
5.发送请求并获得返回结果
5.1发送同步请求:调用execute()方法,返回Response<T>对象,T为我们定义的实体类,调用body()方法就能拿到我们定义的返回类型的对象
Response<LoginResponseModel> responseModelLogin= call.execute();
System.out.println(responseModelLogin.body());
5.2 发送异步请求:调用enqueue方法
call.enqueue(new Callback<LoginResponseModel>() {
public void onResponse(Call<LoginResponseModel> call, Response<LoginResponseModel> response) {
System.out.println(response.body());
}
public void onFailure(Call<LoginResponseModel> call, Throwable throwable) {
throwable.printStackTrace();
}
});