关于Retrofit 2.0的使用

前言

前不久retrofit 2.0正式发布,一直很想试试看这款很火的网络库,所以最近有点时间稍微研究了下retrofit 2.0的使用。苦于网上虽然有很多相关教程,但是很少有代码示例和使用说明,所以,我写点自己对于retrofit使用上的理解,并附上自己的demo源码。

配置

在工程里添加网络访问权限是必须的,所以在AndroidManifest.xml中添加如下代码

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

在app/build.gradle引入下列库

compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
compile 'com.squareup.okhttp3:okhttp:3.0.0'
compile 'com.google.code.gson:gson:2.5'

coverter-gson可以方便的把返回结果转成对象模型,而converter-scalars则可以把返回结果转成String。
如果需要将返回数据转成其他类型,也可以引入其他一些包

compile 'com.squareup.retrofit2:converter-jackson'
compile 'com.squareup.retrofit2:converter-moshi'
compile 'com.squareup.retrofit2:converter-protobuf'
compile 'com.squareup.retrofit2:converter-wire'
compile 'com.squareup.retrofit2:converter-simplexml'

使用

定义一个接口,用于http请求

public interface GitHubService {

    @GET("users")
    Call<String> listRepos();

    /**
     * 参数比较少的情况下,可以直接传出参数名和参数值
     * @param page 参数值
     * @return 返回请求
     */
    @GET("repositories/892275/contributors")
    Call<String> repos(@Query("page")int page);

    /**
     * 参数比较多时,可以以map的形式传入参数名和值
     * @param options 参数Map
     * @return 返回请求
     */
    @GET("user/repos")
    Call<String> getRequestWithMap(@QueryMap Map<String, String> options);

    @FormUrlEncoded
    @POST("/some/endpoint")
    Call<String> getPostWithMap(@FieldMap Map<String, String> names);

    /**
     * 其他的一些使用方式可以参考官方使用说明
     * http://square.github.io/retrofit/
     */

创建Retrofit 实例

Retrofit retrofit = new Retrofit.Builder()
                            .baseUrl("https://api.github.com/")
                            //解析结果为需要的类型
                            .addConverterFactory(ScalarsConverterFactory.create())
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();

发起请求

GithubService service = getInstance().create(GitHubService.class);
Call<String> repos = service.listRepos();
        repos.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, retrofit2.Response<String> response) {
                String str = response.body();
                text.setText(str);
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.i("info",t.getMessage());
            }
        });

注意事项

  1. baseUrl以“/结尾”,多为域名,而@URL则不以“/”
  2. 文中仅列举了两个get请求的方式,其他请求方式参照官网介绍Retrofit 官方介绍
  3. 初次接触retrofit,不足之处还望见谅,后续对retrofit有新的见解将更新此文
  4. demo地址:RetrofitDemo
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值