java retrofit_Retrofit结合RxJava使用指南

Retrofit结合RxJava使用指南

Retrofit是一个当前很流行的网络请求库, 官网的介绍是: "Type-safe HTTP client for Android and Java". 本文介绍Retrofit的使用.

先介绍单独使用Retrofit进行网络请求, 后面主要介绍和RxJava结合的请求, 有实例代码.

Retrofit单独使用

Setup

首先在manifest中加上网络权限:

然后在app/build.gradle中加上依赖:

compile 'com.squareup.retrofit2:retrofit:2.1.0'

compile 'com.google.code.gson:gson:2.8.0'

compile 'com.squareup.retrofit2:converter-gson:2.1.0'

准备API和model类

本例子中使用Github API做请求.

以Github的Root Endpoint为例:

https://api.github.com.

首先, 我们在命令行发送:

curl https://api.github.com

或者在Postman发送这个请求, 两种方法都可以得到结果.

这个请求返回的是一个json.

利用这个网站: jsonschema2pojo, 可以用json生成一个java类, 比如上面这个, 我们给它起名字叫Endpoints.java.

之后例子中的API都是这种方式, 先发送请求得到json, 然后转成java的model类.

利用Retrofit发送请求并得到结果

首先写一个ServiceGenerator类, 用于生成service:

public class ServiceGenerator {

public static final String API_BASE_URL = "https://api.github.com";

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 createService(Class serviceClass) {

Retrofit retrofit = builder.client(httpClient.build()).build();

return retrofit.create(serviceClass);

}

}

这里指定了我们的base url.

createService()方法返回的是一个泛型.

然后我们创建GithubService, 注意这是一个接口:

import com.ddmeng.helloretrofit.data.models.Endpoints;

import retrofit2.Call;

import retrofit2.http.GET;

import retrofit2.http.Url;

public interface GitHubService {

@GET

Call getAllEndpoints(@Url String url);

}

这里@GET指定了是一个GET请求, 因为我们请求的就是base url, 所以是这样写的.

Endpoints类是这个请求所返回的json转化的java类.

好了, 准备工作做完了, 现在就可以请求并得到结果:

请求github api的root url, 得到所有的endpoints:

GitHubService gitHubService = ServiceGenerator.createService(GitHubService.class);

Call endpointsCall = gitHubService.getAllEndpoints("");

endpointsCall.enqueue(new Callback() {

@Override

public void onResponse(Call call, Response response) {

Endpoints endpoints = response.body();

String repositoryUrl = endpoints.getRepositoryUrl();

LogUtils.i(repositoryUrl);

Toast.makeText(MainActivity.this, "repository url: " + repositoryUrl, Toast.LENGTH_LONG).show();

}

@Override

public void onFailure(Call call, Throwable t) {

}

});

说明:

首先利用前面的ServiceGenerator来创建Service, 然后调用接口中定义的getAllEndpoints()方法, 此处传入了空字符串, 因为我请求的就是base url.

同步和异步

这里注意用Retrofit请求的返回值是Call (后面我们还会介绍用RxJava的情形), 泛型T是model类型, 它有两个方法:

execute()是同步方法, 返回Response;

enqueue()是异步方法, 在上面的例子中用的就是这个

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值