Android-网络框架04Retrofit2.0+RxJava

Retrofit官网: https://github.com/square/retrofit
文档 http://square.github.io/retrofit/

本文的意义

随着Google对HttpClient 摒弃,和Volley的逐渐没落,OkHttp开始异军突起,而Retrofit则对okHttp进行了强制依赖。
Retrofit实质上就是对okHttp的封装
现在的Android开发者不会Retrofit + RXJava就感觉跟不上时代了一样,所以小试一下
转载请注明出处 ethan_xue博客

具体步骤

使用方法可查看官网。
按照下面步骤简单几步使用起来。
说明:涉及RXJava的用法直接跳到第5步

(1)添加网络访问权限并添加库依赖
<uses-permission android:name="android.permission.INTERNET" />
compile 'com.squareup.retrofit2:retrofit:2.2.0'
compile 'com.squareup.retrofit2:converter-gson:2.2.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'io.reactivex:rxandroid:1.2.1'
(2)建Interface
public interface TestGetService {
    @GET("adat/sk/{cityId}.html")
    Call<ResponseBody> getWeather(@Path("cityId") String cityId);
}
(3)异步调用
Retrofit retrofit = new Retrofit.Builder()
                //这里建议:- Base URL: 总是以/结尾;- @Url: 不要以/开头
                .baseUrl("http://www.weather.com.cn/")
                .build();
        TestGetService apiStores = retrofit.create(TestGetService.class);
        Call<ResponseBody> call = apiStores.getWeather("101010100");
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    Log.e("xue", "response=" + response.body().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e("xue", "onFailure=" + t.getMessage());
            }
        });
(4)GSON

// 上面的天气:http://www.weather.com.cn/adat/sk/101010100.html
新建bean文件

public class WeatherJson {
    //weatherinfo需要对应json数据的名称,我之前随便写了个,被坑很久
    private Weatherinfo weatherinfo;

    public Weatherinfo getWeatherinfo() {
        return weatherinfo;
    }

    public void setWeatherinfo(Weatherinfo weatherinfo) {
        this.weatherinfo = weatherinfo;
    }

    //city、cityid必须对应json数据的名称,不然解析不了
    public class Weatherinfo {
        private String city;
        private String cityid;
        private String temp;
        private String WD;
        private String WS;
        private String SD;
        private String WSE;
        private String time;
        private String isRadar;
        private String Radar;
        private String njd;
        private String qy;
        //这里省略get和和set方法
    }
}

修改Interface里的ResponseBody为WeatherJson

public interface TestGetService {
    @GET("adat/sk/{cityId}.html")
    Call<WeatherJson> getWeather(@Path("cityId") String cityId);
}

添加addConverterFactory(GsonConverterFactory.create())

Retrofit retrofit = new Retrofit.Builder()
                //这里建议:- Base URL: 总是以/结尾;- @Url: 不要以/开头
                .baseUrl("http://www.weather.com.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        TestGetService apiStores = retrofit.create(TestGetService.class);
        Call<WeatherJson> call = apiStores.getWeather("101010100");
        call.enqueue(new Callback<WeatherJson>() {
            @Override
            public void onResponse(Call<WeatherJson> call, Response<WeatherJson> response) {
                Log.e("xue", "getWeatherinfo=" + response.body().getWeatherinfo().getCity());
            }

            @Override
            public void onFailure(Call<WeatherJson> call, Throwable t) {

            }
        });
(5)RxJava

修改interface为

public interface TestGetService {
    @GET("adat/sk/{cityId}.html")
    Observable<WeatherJson> getWeather(@Path("cityId") String cityId);
}

增加.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
代码修改为

Retrofit retrofit = new Retrofit.Builder()
                //这里建议:- Base URL: 总是以/结尾;- @Url: 不要以/开头
                .baseUrl("http://www.weather.com.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        TestGetService apiStores = retrofit.create(TestGetService.class);

        Observable<WeatherJson> observable = apiStores.getWeather("101010100");
        observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<WeatherJson>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(WeatherJson weatherJson) {
                        Log.e("mylog", weatherJson.getWeatherinfo().getCity());
                    }
                });
总结:

这里是小试一下,没有做封装,封装可参考https://github.com/Tamicer/Novate
感觉代码比其他框架变多了,优点就是rxjava的优点

参考

http://blog.csdn.net/liangdong131/article/details/51791034

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值