您的位置:首页 > 其它

Retrofit框架基本使用

2016-04-20 16:16 274 查看
什么是Retrofit框架?

Retrofit(出自square)是一个android 平台上一个http请求库,使得网络请求变的更加容易,从而让开发者有更多把重心心放在业务逻辑处理上.


Retrofit Api调用

场景:从网络获取数据并转换成相应的bean

1.引入Retrofit相关库

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'io.reactivex:rxandroid:1.1.0'


2.编写请求api

public interface JokeService {
@Headers("apikey:d21e61b696755d2ca3d1d3484bcc5331")
@GET("showapi_open_bus/showapi_joke/joke_text")
Call<ArrayList<JokeBean>> listJokes(@Query("page") String page);

@Headers("apikey:d21e61b696755d2ca3d1d3484bcc5331")
@GET("showapi_open_bus/showapi_joke/joke_text")
Observable<ArrayList<JokeBean>> listJokesRx(@Query("page") String page);
}


3.构建Retrofit对象和发送请求

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://apis.baidu.com/")
.addConverterFactory(MyConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
JokeService service = retrofit.create(JokeService.class);
Call<ArrayList<JokeBean>> call = service.listJokes(1 + "");
call.enqueue(new Callback<ArrayList<JokeBean>>() {
@Override
public void onResponse(Call<ArrayList<JokeBean>> call, Response<ArrayList<JokeBean>> response) {
Log.e("Retrofit", response.body().toString());
}

@Override
public void onFailure(Call<ArrayList<JokeBean>> call, Throwable t) {
Toast.makeText(MainActivity.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});


结合RxJava

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://apis.baidu.com/")
.addConverterFactory(MyConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
JokeService service = retrofit.create(JokeService.class);
Observable<ArrayList<JokeBean>> observable = service.listJokesRx("" + 1);
observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<ArrayList<JokeBean>>() {
@Override
public void onCompleted() {
Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_SHORT).show();
}

@Override
public void onError(Throwable e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}

@Override
public void onNext(ArrayList<JokeBean> jokeBeans) {
Log.e("Retrofit", jokeBeans.toString());
}
});


demo下载地址:

http://download.csdn.net/detail/qinwei1993/9497163

以上就是Retrofit api 调用过程,如果大家想要深入了解不妨看一下

Retrofit分析-漂亮的解耦套路 stay讲很清楚,也很容易理解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: