Retrofit 2.0快速集成

2018-05-19  本文已影响0人  boyrt

不写android原生大概已经1年半了,突然要用到Retrofit框架,突然蒙圈了,不知道从哪里开始。因此记录下如何使用(⊙﹏⊙)b
因本文不是详细介绍Retrofit框架,主要是介绍如何快速集成到项目用并使用,因此需要一定的Retroift基础。

1.使用Retrofit

依赖
创建接收服务器返回数据的类
创建用于描述网络请求的接口
创建Retrofit实例
创建请求接口实例
发送请求
处理返回数据

1.1 依赖

build.gradle文件中添加Retrofit2.0依赖,并根据项目需要进行转换器的依赖添加。
Retrofit官方教程

compile 'com.squareup.retrofit2:retrofit:2.4.0'
//转换器(选配)
//GSON
compile 'com.squareup.retrofit2:converter-gson:2.+'
//Jackson
compile 'com.squareup.retrofit2:converter-jackson:x.x.x'
//simplexml
compile 'com.squareup.retrofit2:converter-simplexml:x.x.x'
//Scalars (primitives, boxed, and String):
compile 'com.squareup.retrofit2:converter-scalars:x.x.x'

1.2 创建接收服务器返回数据的类

1.3 创建用于描述网络请求的接口

public interface ApiService {
    @GET("new/{id}")
    Call<ResponseBody> getNew(@Path("id") int id);
}

1.4 创建Retrofit实例

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://localhost:8081/")
        ...
        .build();

1.5 创建请求接口实例

#通过Retrofit创建ApiService对象
ApiService service = retrofit.create(ApiService.class);

1.6 发送请求

#发送请求(接口调用)--支持同步和异步:execute 、enqueue
Call<ResponseBody> call = service.getNew(1);

//此处执行请求,和okhttp一样,区别在于回调方法是在主线程执行
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //TODO 该回调方法什么时候响应
    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        t.printStackTrace();
    }
});

1.7 处理返回数据

response.body()

相关文章链接:
Retrofit注解简介

上一篇下一篇

猜你喜欢

热点阅读