Retrofit的初步使用

来源:互联网 发布:linux组织文件目录结构 编辑:程序博客网 时间:2024/04/19 21:24

纪录下Retrofit的初步使用笔记。Retrofit用的还是okhttp,不过做了进一步的拓展,调用起来比单纯的使用okhttp方便多了(先理解)。

文章以解析https://api.github.com/users/Jayden37 为例子。

Retrofit官网地址http://square.github.io/retrofit/

首先,在清单文件中加上网络的权限<uses-permission android:name="android.permission.INTERNET" />,然后在主模块的build.gradle配置上依赖,用的是2.1.0的版本,以官网最新的版本为准。

    compile 'com.squareup.retrofit2:retrofit:2.1.0'    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
下一步,定义一个接口,用的是注解的方式,@Get代表的是get请求方式,/users/{user}是请求地址的拼接字符,后面配置的时候会配置上基址https://api.github.com。{user}是占位符,后面调用的时候会传值过来,如传字符串“Jayden37”。方法repo是自己取的名字,@Path代表拼接的字符,就是传过来的字符取代{user}占位符的位置。repo方法会返回一个Call的对象。

public interface APIInterface {    /**https://api.github.com/users/Jayden37*/    @GET("/users/{user}")    Call<TestModel> repo(@Path("user") String user);}
TestModel对应的是https://api.github.com/users/Jayden37 返回的gson解析后的Bean对象。这里没有写完整。只写了第一个值。

public class TestModel {    private String login;    public String getLogin() {        return login;    }    public void setLogin(String login) {        this.login = login;    }    public TestModel(String login) {        this.login = login;    }}
然后在MainActivity调用Retrofit的方法。先获取Retrofit对象,baseUrl配置的就是基址,会拼接你的请求前面,如APIInterface的@Get("users/{user}"),拼接后就是https://api.github.com/users/{user},addConverterFactory是Gson解析用到的。 调用retrofit.create获取到接口对象apiInterface,apiInterface调用方法repo(Jayden37)传入占位符的值,所以接口{user}替代为Jayden37,地址变为https://api.github.com/users/Jayden37  ,返回Call对象modelCall,modelCall执行enqueue异步操作,会回调到主线程onResponse、onFailure成功和失败两个方法。

        Retrofit retrofit = new Retrofit.Builder()                .baseUrl("https://api.github.com")                .addConverterFactory(GsonConverterFactory.create())                .build();        APIInterface apiInterface = retrofit.create(APIInterface.class);        Call<TestModel> modelCall = apiInterface.repo("Jayden37");        modelCall.enqueue(new Callback<TestModel>() {            @Override            public void onResponse(Call<TestModel> call, Response<TestModel> response) {                Log.i(TAG,response.body().getLogin());            }            @Override            public void onFailure(Call<TestModel> call, Throwable t) {                Log.e(TAG,"请求失败="+t.getMessage()+":"+t.toString());            }        });


打印的结果为:jayden37代表请求

成功。

项目地址:https://github.com/37Jayden/RetrofitDemo




0 0