Retrofit2的使用简单介绍

先接触的时候肯定先去网上找了找相关资料,大部分是Retrofit1.9,最新的版本都2了,所以看了这个帖子http://blog.csdn.net/u012301841/article/details/49685677;这里先感谢下;

例子的代码直接贴出来:首先是Retrofit的初始化这里使用Gson解析的,所以:

private static Retrofit initRetrofit() {
        OkHttpClient httpClient = new OkHttpClient();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient = new OkHttpClient.Builder().addInterceptor(logging).build();
        }
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
        return new Retrofit.Builder().baseUrl(API.BASEURL).addConverterFactory(GsonConverterFactory.create(gson))
                .client(httpClient).build();
    }

  接着就是常规的做法:

public interface gitapi {
    @GET("/users/{user}")
     Call<User> getFeed(@Path("user")String user);
}

  

  Retrofit retrofit = initRetrofit();
                gitapi api = retrofit.create(gitapi.class);
                api.getFeed(user).enqueue(new Callback<User>() {
                    @Override
                    public void onResponse(Call<User> call, Response<User> response) {
                        Log.i("MainActivity", response.body().getName());
                    }

                    @Override
                    public void onFailure(Call<User> call, Throwable t) {

                    }
                });

  

posted @ 2016-04-10 20:46  fightzhao  阅读(919)  评论(0编辑  收藏  举报