Retrofit网络框架搭建

本文介绍如何结合Retrofit和RxJava构建网络请求框架。通过创建Retrofit实例并配置Gson转换器及RxJava适配器,实现异步请求天气信息的功能。最终通过MainActivity发起请求并在UI线程更新结果显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

概述

Retrofit与RxJava结合起来用的比较多,现在我们一起来搭建一个基于Retrofit和RxJava的框架,方便以后的使用,搭建框架以前我们需要引入相应的库引用地址,如下所示:
这里写图片描述

代码

假设我们的项目名称为APP,我们需要写三个文件,首先是配置Retrofit

public class AppRetrofit {
    private final Retrofit mRetrofit;
    private final AppApi appApi;

    public AppRetrofit(){
        //添加gson转换;
        mRetrofit = new Retrofit.Builder().baseUrl("http://www.weather.com.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        appApi = mRetrofit.create(AppApi.class);
    }
    public AppApi getGankApiService(){
        return appApi;
    }
}

然后是我们请求的方法以及携带的参数,写在AppApi中

public interface AppApi {
    @GET("adat/sk/{cityId}.html")//注意参数名称必须一样 @Path表示将参数进行匹配,与{}结合使用
    Observable<WeatherInfo> getWeatherInfo(@Path("cityId") String cityId);
}

最后我们写一个单例来获取这个AppApi

public class AppFactory {
    private static Object monitor = new Object();
    private static AppApi sAppApi;
    public static AppApi getGankApi() {
        if (sAppApi == null) {
            synchronized (monitor) {
                if (sAppApi == null) {
                    sAppApi = new AppRetrofit().getGankApiService();
                }
            }
        }
        return sAppApi;
    }
}

经过上面的三个步骤,关于Retrofit和RxJava的框架已经搭建好了,下面我们尝试着去发一个请求。

public class MainActivity extends AppCompatActivity {
    private TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textview);
        Observable<WeatherInfo> weatherInfo = AppFactory.getGankApi().getWeatherInfo("101010100");
        weatherInfo.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<WeatherInfo>() {
                    @Override
                    public void call(WeatherInfo weatherInfo) {
                        textView.setText(weatherInfo.toString());
                    }
                });
    }
}

代码很简单,我们先获取了一个AppApi的单例对象,然后调用方法发起了请求,运行效果如下
这里写图片描述

可以看到,请求成功了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值