Retrofit是什么
Retrofit是一个类型安全的HTTP客户端,支持Android和Java.它是Square公司开源的项目,当前版本2.0。
在实际开发中,我们Retrofit配合OKHTTP来使用。我们使用OKHTTP当做传输层,使用Retrofit在OKHTTP之上,使用Java的接口描述我们的HTTP协议。
简单的说: 使用Retrofit转换HTTP 的API协议成一个java的Interface服务,我们直接使用java类会方便好多。
Retrofit怎么用
添加依赖
compile 'com.squareup.retrofit2:retrofit:2.1.0'
//转换器,处理json格式的数据
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
Retrofit2.0中已经依赖了OKHTTP,避免重复引用OKHTTP,可以使用自己的OKHTTP:
compile ('com.squareup.retrofit2:retrofit:2.1.0') {
// 排除依赖okhttp
exclude module: 'okhttp'
}
compile 'com.squareup.okhttp3:okhttp:3.4.1' //重新依赖okhttp
如果你要请求这么一个api:
//查看github上某个repo的contributors
https://api.github.com/repos/{owner}/{repo}/contributors
首先,需要创建这样一个接口
public interface Github {
@GET("/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> getContributors(
@Path("owner") String owner,
@Path("repo") String repo);
}//这里的Contributor是JavaBean
接着,在Activity中创建一个Retrofit对象
public class MainActivity extends AppCompatActivity {
public static final String API_URL = "https://api.github.com";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
....
}
}
然后,就可以通过retrofit创建Github对象获取数据了:
//创建Github接口对象
Github github = retrofit.create(Github.class);
Call<List<Contributor>> call = github.getContributors("square", "retrofit");
//设置回调接口
call.enqueue(new Callback<List<Contributor>>() {
@Override
public void onResponse(Call<List<Contributor>> call, Response<List<Contributor>> response) {
for (Contributor contributor : response.body()) {
Log.e("contributor ", contributor.toString());
}
}
@Override
public void onFailure(Call<List<Contributor>> call, Throwable t) {
Log.e("contributor number", "failure");
}
});
你还可以移除一个请求。Retrofit 1.x版本没有直接取消正在进行中任务的方法的。在2.x的版本中,Service 的模式变成Call的形式的原因是为了让正在进行的事务可以被取消。要做到这点,你只需调用call.cancel()。
call.cancel()
Retrofit虽然在使用方式看上去和Volley的方式不一样,但它们的本质是一样的。使用Volley时你必须先创建一个Request对象,以及一个请求成功和失败的Listener,然后把这个请求放到RequestQueue中,最后NetworkDispatcher会请求服务器获得数据。而Retrofit则是通过描述一个接口来定义一个请求,再将这个请求加入到请求队列中。
URL的定义方式
Retrofit 2.0使用了新的URL定义方式。Base URL与@Url 不是简单的组合在一起而是和的处理方式一致。用下面的几个例子阐明。
public interface APIService {
@POST("user")
Call<User> login();
}
public void doSomething() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.demo.come/base/home")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//最后的url是http://api.demo.come/base/user
public interface APIService {
@POST("user")
Call<User> login();
}
public void doSomething() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.demo.come/base/home/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//最后的url是http://api.demo.come/base/home/user
public interface APIService {
@POST("/user")
Call<User> login();
}
public void doSomething() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.demo.come/base/home/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//最后的url是http://api.demo.come/user
对于 Retrofit 2.0中新的URL定义方式,这里是我的建议:
- Base URL: 总是以 /结尾
- @Url: 不要以 / 开头
例如:
public interface APIService {
@POST("user/list")
Call<User> login();
}
public void doSomething() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://api.demo.come/base/")
.addConverterFactory(GsonConverterFactory.create())
.build();
}
//最后的url是http://api.demo.come/base/user/list
当然,在Retrofit 2.0中我们也可以在@Url里面定义完整的URL,这时Base URL会被忽略。
public interface Github {
@GET("https://api.github.com/repos/{owner}/{repo}/contributors")
Call<List<Contributor>> getContributors(
@Path("owner") String owner,
@Path("repo") String repo);
}
public static final String API_URL = "https://www.baidu.com";
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create()).build();
//最后的url是https://api.github.com/repos/{owner}/{repo}/contributors,忽略了baseUrl