一.Retrofit的概念
Retrofit 是 Square 公司开发的,面向Android和Java的,一个类型安全的网络请求客户端。
Retrofit 是 Square 公司开发的,面向Android和Java的,一个类型安全的网络请求客户端。
通过注解的方式,设置请求类型;如:@POST("")
二. Retrofit的基本使用
<1>Retrofit retrofit = new Retrofit.Builder()
....build(); // Retrofit初始化
<2>public interface GitHub { // 订阅请求接口
@(GET“”) // 注释描述请求类型
Call<List<String>> getDatas()
}
<3>
Call<List<String>> call = retrofit.create(GitHub.class). getDatas(“param1”, “param2”); // 调用接口,重写回调方法
三:实例
首先导入依赖
compile 'io.reactivex:rxjava:1.0.14'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.squareup.retrofit2:retrofit:2.0.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0'
<1>Retrofit的普通写法
private void testRetrofit(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
Call<List<String>> call = retrofit.create(GitHub.class).itemDatas("zhangkekekeke", "RxJavaObserver");
call.enqueue(new Callback<List<String>>() {
@Override
public void onResponse(Call<List<String>> call, Response<List<String>> response) {
Observable.from(response.body())
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
Log.d("RxJava_R", s + ")");
}
});
}
@Override
public void onFailure(Call<List<String>> call, Throwable t) {
Log.d(TAG, t.getMessage());
}
});
}
public interface GitHub {
@GET("/{owner}/{txt}/master/jsondata")
Call<List<String>> itemDatas(
@Path("owner") String owner,
@Path("txt") String repo
);
}
<2>RxJava+Retrofit 组合写法
public class RetrofitActivity extends RxAppCompatActivity {
public static final String API_URL = "https://raw.githubusercontent.com/";
private Retrofit retrofit;
private Subscription subscription;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_retrofit);
//初始化Retrofit
retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
//发送请求,返回数据的Observable
subscription = retrofit.create(GetGithub.class)
.itemDatas("zhangkekekeke", "RxJavaObserver")
.subscribeOn(Schedulers.io())
.flatMap(strings -> Observable.from(strings))
.subscribe(s -> {
Log.d("RxJava_R", s);
});
}
//定义请求接口
public interface GetGithub {
@GET("/{owner}/{txt}/master/jsondata")
Observable<List<String>> itemDatas(
@Path("owner") String owner,
@Path("txt") String repo);
}
@Override
protected void onDestroy() {
super.onDestroy();
//取消订阅~
if (subscription != null) {
subscription.unsubscribe();
subscription = null;
}
}
}