Android开发之初学Retrofit

前言:

随着现在的OKHttp框架的使用,Retrofit也越来越多的用到了项目当中。先来简单的介绍一下Retrofit的使用!先贴张图:


Retrofit的Github地址:https://github.com/square/retrofit

接下来先来说说使用步骤:

步骤一:引入

1.首先要有获取网络权限,清单文件中获取权限;2.在APP下面的build.gradle中添加引用;

<uses-permission android:name="android.permission.INTERNET"/>

Retrofit的引用:
compile 'com.squareup.retrofit2:retrofit:2.2.0'

Retrofit使用Gson的引用:

compile 'com.squareup.retrofit2:converter-gson:2.1.0'

Retrofit结合RxJava使用的引用

compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
compile 'io.reactivex:rxjava:1.1.8'
compile 'io.reactivex:rxandroid:1.2.1's

步骤二:配置Retrofit

public class ApiModule {
    private static String ENDPOINT = "http://api.douban.com/";//定义一个base URL
    private static Retrofit.Builder builder;//配置Retrofit
    private static Map<Class, Object> apiModule;
    private static OkHttpClient httpClient;//OkHttpClient配置

    static {
        httpClient = new OkHttpClient();
        apiModule = new ConcurrentHashMap<>();
        builder = new Retrofit.Builder()
                .baseUrl(ENDPOINT)
                .addConverterFactory(GsonConverterFactory.create()); // 添加Gson转换器
    }
    /**
     * 创建api 单例
     */
    public static <T> T of(Class<T> sClass) {
        if (apiModule.containsKey(sClass)) {
            return (T) apiModule.get(sClass);
        }
        Retrofit retrofit = builder.client(httpClient).build();
        T t = retrofit.create(sClass);
        apiModule.put(sClass, t);
        return t;
    }
}

步骤三:创建接口用于引用

public interface DouBanInterface {
    // 获取库, 获取的是数组
    @GET("v2/movie/in_theaters")
    Call<ListDTO<SubjectsInfo>> getRepoData(@Query("count") String count);
    // 获取库, 获取的是数组
    @GET("v2/movie/top250")
    Call<ListDTO<SubjectsInfo>> getTop250(@Query("count") String count);
}
其中List是用于存储实体类entity的集合 SubjectsInfo是这个数据的实体类

步骤四:通过拼接参数去访问数据

//获取一个Api实例
douBanInterface = ApiModule.of(DouBanInterface.class);
douBanInterface.getRepoData("20").enqueue(new Callback<ListDTO<SubjectsInfo>>() {
    @Override
    public void onResponse(Call<ListDTO<SubjectsInfo>> call, Response<ListDTO<SubjectsInfo>> response) {
        Log.d("print", "onResponse: " + response.body().toString());

    }

    @Override
    public void onFailure(Call<ListDTO<SubjectsInfo>> call, Throwable t) {
        Toast.makeText(MainActivity.this, "获取数据失败,请检查网络是否连接成功", Toast.LENGTH_SHORT).show();
    }
});
这样Retrofit的基本使用就结束了,我这里只使用到了@GET这个标识符,具体拼接的是时候根据自己的需求来拼接设置就可以了,感谢 豆瓣的数据

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值