Retrofit + Rxjava + RxAndroid实现网络请求

之前自己实现了一个新闻类阅读APP,最近想使用当下流行的Retrofit + Rxjava + RxAndroid + MVP架构来重构一下,本文以每日一文作为数据源API做一个简单的示例,来介绍一下如何使用Retrofit + Rxjava + RxAndroid来实现网络数据请求与解析。

一、配置

在你项目的build.gradle文件中加入如下配置:

    //rxjava
    compile 'io.reactivex:rxandroid:1.2.0'
    compile 'io.reactivex:rxjava:1.1.5'

    //retrofit
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:retrofit:2.2.0'
    compile 'com.squareup.retrofit2:converter-gson:2.2.0'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
    compile 'com.squareup.okhttp:okhttp:2.4.0'

二、生成数据实体

把API返回的Json数据通过Android Studio的GsonFormat插件进行转换生成数据实体类DailyReadEntity(自动构建的代码,很长就不往上贴了)

三、创建请求service接口
今日文章
url:https://interface.meiriyiwen.com/article/today?dev=1
特定日期文章
url:https://interface.meiriyiwen.com/article/day?dev=1&date= + 日期
url 示例:https://interface.meiriyiwen.com/article/day?dev=1&date=20170216

public interface DailyReadService {
    @GET("article/today?dev=1")
    Observable<DailyReadEntity> getTodayDailyRead();
    @GET("article/day?dev=1&date=")
    Observable<DailyReadEntity> getParticularDayDailyRead(@Query("date") int date );
}

四、构建retrofit实例并创建请求service

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://interface.meiriyiwen.com/") //主机URL
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        DailyReadService dailyReadService = retrofit.create(DailyReadService.class);

五、调用请求service中定义的方法请求数据

        dailyReadService.getTodayDailyRead()
                .subscribeOn(Schedulers.io())        //在新线程里面处理网络请求
                .observeOn(AndroidSchedulers.mainThread())  //在主线程里面接受返回的数据
                .subscribe(new Subscriber<DailyReadEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(DailyReadEntity today) {
                        Log.d(TAG,"onNext daily = " + today.toString());
                    }
                });

        dailyReadService.getParticularDayDailyRead(20170511)
                .subscribeOn(Schedulers.io())        //在新线程里面处理网络请求
                .observeOn(AndroidSchedulers.mainThread())  //在主线程里面接受返回的数据
                .subscribe(new Subscriber<DailyReadEntity>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(DailyReadEntity particularDay) {
                        Log.d(TAG,"onNext particularDay = " + particularDay.toString());
                    }
                });

小结:
我自己在实践过程中所遇到的问题是在实现请求服务接口的时候@Path和@Query等接口的使用,查看了一下Retrofit的官方文档和具体接口的注释很快就解决了。另外,这是一个与网络相关的功能,是一个耗时任务需要在子线程中执行。这个时候就看出来这套框架的优点了,你只需调用subscribeOn在新线程中请求,然后调用observeOn在主线程中接受数据,两行代码就解决了,再也不用自己去创建新的线程然后再通过handler通知主线程来刷新数据了。
最后要吐槽一下,昨天在用网易新闻的一个频道实现逻辑做测试的时候始终抛出retrofit2.adapter.rxjava.HttpException: HTTP 403 Forbidden异常,印象里就成功了一把。检查了很多遍也做了很多尝试都不行,耗了一个下午,log中也无其他异常,最后换了一个其他频道,终于可以正常解析了,原来是服务器异常导致的。这个故事告诉我们,有的时候你需要换个角度思考问题。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
好的,以下是一个使用 OkHttp、RetrofitRxJava 的简单 Android 示例。 首先,你需要在你的 build.gradle 文件中添加以下依赖: ``` dependencies { implementation 'com.squareup.okhttp3:okhttp:4.9.1' implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'io.reactivex.rxjava2:rxjava:2.2.19' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' } ``` 这样就可以使用 OkHttp、RetrofitRxJava 的类和方法了。 接下来,你可以在你的代码中定义一个 Retrofit 接口: ``` public interface ApiService { @GET("users/{username}") Observable<User> getUser(@Path("username") String username); } ``` 在这个接口中,我们定义了一个 GET 请求,用于获取一个用户的信息。该请求的 URL 是 "https://api.github.com/users/{username}",其中 {username} 参数将会被替换为实际的用户名。接口返回的数据类型是 User,这是一个简单的类,如下所示: ``` public class User { public final String login; public final int id; public final String avatarUrl; public final String htmlUrl; public User(String login, int id, String avatarUrl, String htmlUrl) { this.login = login; this.id = id; this.avatarUrl = avatarUrl; this.htmlUrl = htmlUrl; } } ``` 现在,你可以在你的 Activity 或 Fragment 中调用这个接口: ``` ApiService apiService = RetrofitClient.getInstance().create(ApiService.class); apiService.getUser("octocat") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(user -> { // 在这里处理获取到的用户信息 }, throwable -> { // 在这里处理请求失败的情况 }); ``` 该示例将会获取一个名为 "octocat" 的用户的信息,并在获取到数据后将其打印出来。需要注意的是,这个网络请求是在一个新的线程中执行的,以避免阻塞主线程。获取到数据后,我们转换到主线程中,并在观察者的 onNext 回调中处理数据。如果请求失败,则在观察者的 onError 回调中处理错误情况。 希望这个简单的示例可以帮助你理解如何在 Android 中使用 OkHttp、RetrofitRxJava
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值