Android 开发之Retrofit网络框架

来源:互联网 发布:网络诗歌每日一诗 编辑:程序博客网 时间:2024/06/07 04:50

Retrofit与okhttp共同出自于Square公司,retrofit就是对okhttp做了一层封装。把网络请求都交给给了Okhttp,我们只需要通过简单的配置就能使用retrofit来进行网络请求了,其主要作者是Android大神JakeWharton。

1.依赖注入

ompile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包    compile    'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依赖包    compile    'com.squareup.retrofit2:converter-scalars:2.0.0-beta4'//ConverterFactory的String依赖包

2.1

情景模拟,现在我们需要向baseURL(http://www.XXXXXX.cn/)发送GET请求.
步骤一:
利用baseURL创建retrofit对象:

public static final String baseUrl="http://www.XXXXX.cn/";    Retrofit retrofit = new Retrofit.Builder()            .baseUrl(baseUrl)            .addConverterFactory(ScalarsConverterFactory.create())            //增加返回值为Gson的支持(以实体类返回)            .addConverterFactory(GsonConverterFactory.create())            .build();

步骤二:
定义GET方法的接口:(不带参数的get请求)

public interface ApiArea {    interface area{        @GET("/area/list/")        Call<String> getArea();    }}

@GET(“/area/list/”)表示在baseURL的后面加上/area/list/,构成完整的请求路径。
getArea方法是返回Call<string>对象.

步骤三:
利用接口创建对象,(实例化接口),并产生call对象。

ApiArea.area service = retrofit.create(ApiArea.area.class);//这里采用的是Java的动态代理模式        retrofit2.Call<String> call = service.getArea();

步骤四:执行call

call.enqueue(new Callback<String>() {            @Override            public void onResponse(retrofit2.Call<String> call, Response<String> response) {                L.e("OnSuccess"+response.body().toString());            }            @Override            public void onFailure(retrofit2.Call<String> call, Throwable t) {                L.e("OnFailure");            }        });

参考文章:android 介绍Retrofit的简单使用