Retrofit简单介绍和使用

原文地址:

https://futurestud.io/blog/retrofit-getting-started-and-android-client#

Retrofit是什么

对于Retrofit ,官方的描述是:“A type-safe REST client for Android and Java.”它可以通过注解来描述Http请求,URL参数,查询参数,同时,它还支持多个请求体和文件上传。

引入到Android工程

dependencies {  
    // Retrofit & OkHttp
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
}

对于后面的具体版本,一般使用官方最新的版本。
Retrofit 2默认情况下利用okhttp为网络层,在它的基础上建立的。你不需要显式地定义okhttp作为你的项目的依赖性,除非你有一个特定的版本要求。

创建ServiceGenerator

首先是需要创建一个ServiceGenerator 类,它是使用整个框架的核心,它只有一个方法用来创建REST adapter

public class ServiceGenerator {

    public static final String API_BASE_URL = "http://your.api-base.url";

    private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();

    private static Retrofit.Builder builder =
            new Retrofit.Builder()
                    .baseUrl(API_BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create());

    public static <S> S createService(Class<S> serviceClass) {
        Retrofit retrofit = builder.client(httpClient.build()).build();
        return retrofit.create(serviceClass);
    }
}

ServiceGenerator 类使用 Retrofit的restadapter Builder与给定的API库的URL创建一个新的REST客户端。例如,GitHub的API库的网址是https://api.github.com/。参数serviceclass是定义的API请求注释的类或接口。下面显示的具体用法的 Retrofit以及如何定义一个实例的客户端。

JSON映射

使用Retrofit 2时,需要明确的为Retrofit实例添加一个转化器,在上面的build.gradle文件中,为了引入GSON转化器,我们添加了下面这样一行:

compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'  

现在,你可以在Retrofit’s builder上调用:

.addConverterFactory(GsonConverterFactory.create())

使GSON成为Retrofit内部默认的JSON转化器。

Retrofit 请求网络

下面是一个例子,客户端通过Retrofit 从github上面请求数据。首先新建一个GitHubClient 类,定义一个从github上获取一个开源库所有的贡献者的方法:

public interface GitHubClient {  
    @GET("/repos/{owner}/{repo}/contributors")
    Call<List<Contributor>> contributors(
        @Path("owner") String owner,
        @Path("repo") String repo
    );
}

{owner} 和 {repo} 在调用时会被替换成传入的参数,这个方法返回的是
我们想要得到的Contributor集合

Contributor 实体类:

public class Contributor {  
    String login;
    int contributions;
}

在上面添加JSON转化器后,Retrofit 会自动把请求的数据转化成实体类。

最后请求的代码:

 // Create a very simple REST adapter which points the GitHub API endpoint.
    GitHubClient client = ServiceGenerator.createService(GitHubClient.class);

    // Fetch and print a list of the contributors to this library.
    Call<List<Contributor>> call =
        client.contributors("fs_opensource", "android-boilerplate");

    try {
        List<Contributor> contributors = call.execute().body();
    } catch (IOException e) {
        // handle errors
    }

    for (Contributor contributor : contributors) {
        System.out.println(
                contributor.login + " (" + contributor.contributions + ")");
    }

首先通过ServiceGenerator 实例化 GitHubClient ,然后调用 GitHubClient 实例的contributors方法,得到Contributor集合,至此,一次完整的网络请求已经完成。

Demo地址:

http://download.csdn.net/detail/jiangxuqaz/9440960

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值