Android开发之初学Retrofit

来源:互联网 发布:vb程序设计环境介绍 编辑:程序博客网 时间:2024/06/06 04:07

前言:

随着现在的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
原创粉丝点击