Retrofit2是一种为Android和Java提供安全的HTTP客户端,即是一种http客户端框架。可以访问网络请求并将访问的数据转换成你想要的类型。
相关api:http://square.github.io/retrofit/
1.Retrofit2入门
首先在gradle中添加retrofit库和网络权限
1. 定义接口。
使用Retrofit ,首先需要将你的HTTP API改造成Java接口。例如,
public interface ApiService {
@GET("StudentInq")
Call<ResponseBody> getStudents();
}
ApiService 接口定义了一个方法getStudents(),@GET表示该方法是GET请求,该方法没有参数,@GET("StudentInq")中的“StudentInq”是path(相对URL),这个path和baseUrl一起组成了接口的请求全路径,例如baseUrl是“http://localhost:8080/mServer/”,那么全路径就是“http://localhost:8080/mServer/getStudent”。(baseUrl下文会提到)
2. 实例化Retrofit。
a. 首先定义了服务请求的URL,
// 服务请求url
public static final String API_URL = "http://localhost:8080/mServer/";
这个API_URL就是baseUrl,是由ip和端口等组成。
PS: 请求URL,需要以“/”结尾,否则会报错。(敲黑板)
b. 创建Retrofit 实例,
Retrofit retrofit = new Retrofit.Builder().baseUrl(API_URL).build();
通过构造者模式创建了Retrofit ,其中设置了请求的
baseUrl。
c. 接着创建接口实例,
ApiService service = retrofit.create(ApiService.class);
从源码中可以得知,内部使用 了动态代理模式。
d. 下面就可以调用接口中的方法了,
// 调用具体接口方法
Call<ResponseBody> call = service.getStudents();
//异步执行请求
call.enqueue(...);
如果是同步请求,调用execute;而发起一个异步请求则调用enqueue。
完整代码如下:
public class GetTest {
// 服务请求url
public static final String API_URL = "http://localhost:8080/mServer/";
public interface ApiService {
@GET("StudentInq")
Call<ResponseBody> getStudents();
}
public static void main(String[] args) {
getList();
}
/**
* 获取数据
*/
private static void getList() {
// 创建Retrofit实例
Retrofit retrofit = new Retrofit.Builder().baseUrl(API_URL).build();
// 生成ApiService接口代理
ApiService service = retrofit.create(ApiService.class);
// 调用具体接口方法
Call<ResponseBody> call = service.getStudents();
//异步执行请求
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
// TODO Auto-generated method stub
try {
System.out.println(response.body().string());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> arg0, Throwable arg1) {
// TODO Auto-generated method stub
}
});
}
}