android retrofit的基本使用

本文记录一下基本的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)当请求参数是在链接后面的时候
       http://api.douban.com/v2/movie/top250?start=5&count=20
       业务bean需要这样写
        
@GET("/v2/movie/top250")
        Call<MovieRespBase> loadMovieData(
             @Query("start")int start,
             @Query("count")int count
        );

(2)当请求链接是动态的时候
       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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值