本文记录一下基本的retrofit使用,入门级别的.
首先在项目下依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2' compile 'com.squareup.retrofit2:converter-gson:2.0.2'
############################ get请求 ################################
//请求实体<pre name="code" class="java">public class Repo {
public String login;
public int contributions;
public Repo(String login, int contributions) {
this.login = login;
this.contributions = contributions;
}
}
//业务接口
public interface APIService {
@GET("/repos/square/retrofit/contributors")
Call<List<Repo>> loadRepo();
}
//测试类
public class TestRetrofit1 {
public static final String API_URL = "https://api.github.com";
public static void main(String[] args) throws IOException {
Retrofit mRetrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = mRetrofit.create(APIService.class);
Call<List<Repo>> repoCall = service.loadRepo();
/*
下面表示同步请求,需要写到一个线程中
List<Repo> mRepo = repoCall.execute().body();
for (int i = 0; i < mRepo.size(); i++) {
System.out.println(""+mRepo.get(i).login);
}*/
/***
* 下边为异步请求
*/
repoCall.enqueue(new Callback<List<Repo>>() {
@Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
if(response.isSuccessful()){
List<Repo> mRepo = response.body();
if(mRepo != null && !mRepo.isEmpty()){
for (int i = 0; i < mRepo.size(); i++) {
System.out.println(""+mRepo.get(i).login);
}
}
}
}
@Override
public void onFailure(Call<List<Repo>> call, Throwable t) {
}
});
}
}
另外需要注意:
(1)当请求参数是在链接后面的时候业务bean需要这样写http://api.douban.com/v2/movie/top250?start=5&count=20
(2)当请求链接是动态的时候@GET("/v2/movie/top250") Call<MovieRespBase> loadMovieData( @Query("start")int start, @Query("count")int count );
https://api.github.com/repos/square/retrofit/contributors
业务bean需要这样写
@GET("/repos/{square}/{retrofit}/contributors") Call<List<Repo>> loadRepo( @Path("square")String square, @Path("retrofit")String retrofit );
附上一个链接
http://wuxiaolong.me/2016/01/15/retrofit/
还有一篇讲的很详细的注解
http://blog.csdn.net/guiman/article/details/51480497