近几年,Retrofit犹如燎原之火搬席卷了整个Android界。要是不懂Retrofit,简直不好意思出门。。。
由于近几个项目都没用到Retrofit,无奈只能业余时间自己撸一下,写的不好的地方,还请不吝赐教。
要集成retrofit,在app的bild.gradle中添加库以来就可以:
compile 'com.squareup.retrofit2:retrofit:2.3.0'
如果需要集成json解析,还需要添加库:
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
如果还需要集成rxjava,还需要添加库:
compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
添加库完毕,接下来需要定义请求接口:
public interface TestService {
/**
* 获取新闻 使用rxjava
* @return
*/
@POST(AppConstance.NEWS_URL)
Observable<NewsBean> getNewsWithRxJava(@Query("key") String key, @Query("type") String type);
/**
* 获取新闻 不使用rxjava
* @return
*/
@POST(AppConstance.NEWS_URL)
Call<ResponseBody> getNewsWithoutRxJava(@Query("key") String key, @Query("type") String type);
}
这个接口是我在聚合数据申请的测试接口,我将其分为两种情况:使用rajava、不使用rxjava。
正常使用中,都会将Retrofit进行封装,我在这里将其简单的封装:
public class RetrofitUtil {
private volatile static RetrofitUtil sInstance;
private Retrofit mRetrofit;
private TestService mTestService;
private RetrofitUtil(){
mRetrofit = new Retrofit.Builder()
.baseUrl(AppConstance.APP_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
mTestService = mRetrofit.create(TestService.class);
}
public static RetrofitUtil getInstance(){
if (sInstance == null){
synchronized(RetrofitUtil.class){
if (sInstance == null){
sInstance = new RetrofitUtil();
}
}
}
return sInstance;
}
public TestService getTestService(){
return mTestService;
}
}
万事具备,现在开始在Activity中测试Retrofit。
xml文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.shenchanghui.retrofit2withrxjava2_demo.MainActivity">
<Button
android:id="@+id/btn_get_news_with_rx_java"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:text="获取新闻(使用rxjava)" />
<Button
android:id="@+id/btn_get_news_without_rx_java"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/btn_get_news_with_rx_java"
android:text="获取新闻(不使用Rxjava)" />
</RelativeLayout>
在Activity中请求数据,首先,不使用rajava:
findViewById(R.id.btn_get_news_without_rx_java).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
long time1 = System.currentTimeMillis();
Call<ResponseBody> call = RetrofitUtil.getInstance().getTestService()
.getNewsWithoutRxJava("8bf17cf1c321723f060d5dc5c4da871a", "top");
long time2 = System.currentTimeMillis();
Log.e("MainActivity", "请求耗时:" + (time2 - time1) + "ms");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
String result = response.body().string();
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
Log.e("MainActivity", "Thread.currentThread():" + Thread.currentThread());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_SHORT).show();
}
});
}
});
运行项目,成功获取返回的json字符串。
创建实体类,用GsonFormat插件将获取的json字符串生成实体类,用以解析json。
实体类:
public class NewsBean {
private String reason;
private ResultBean result;
private int error_code;
@Override
public String toString() {
return "NewsBean{" +
"reason='" + reason + '\'' +
", result=" + result +
", error_code=" + error_code +
'}';
}
public String getReason() {
return reason;
}
public void setReason(String reason) {
this.reason = reason;
}
public ResultBean getResult() {
return result;
}
public void setResult(ResultBean result) {
this.result = result;
}
public int getError_code() {
return error_code;
}
public void setError_code(int error_code) {
this.error_code = error_code;
}
public static class ResultBean {
private String stat;
private List<DataBean> data;
@Override
public String toString() {
return "ResultBean{" +
"stat='" + stat + '\'' +
", data=" + data +
'}';
}
public String getStat() {
return stat;
}
public void setStat(String stat) {
this.stat = stat;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean {
private String uniquekey;
private String title;
private String date;
private String category;
private String author_name;
private String url;
private String thumbnail_pic_s;
private String thumbnail_pic_s02;
private String thumbnail_pic_s03;
@Override
public String toString() {
return "DataBean{" +
"uniquekey='" + uniquekey + '\'' +
", title='" + title + '\'' +
", date='" + date + '\'' +
", category='" + category + '\'' +
", author_name='" + author_name + '\'' +
", url='" + url + '\'' +
", thumbnail_pic_s='" + thumbnail_pic_s + '\'' +
", thumbnail_pic_s02='" + thumbnail_pic_s02 + '\'' +
", thumbnail_pic_s03='" + thumbnail_pic_s03 + '\'' +
'}';
}
public String getUniquekey() {
return uniquekey;
}
public void setUniquekey(String uniquekey) {
this.uniquekey = uniquekey;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAuthor_name() {
return author_name;
}
public void setAuthor_name(String author_name) {
this.author_name = author_name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getThumbnail_pic_s() {
return thumbnail_pic_s;
}
public void setThumbnail_pic_s(String thumbnail_pic_s) {
this.thumbnail_pic_s = thumbnail_pic_s;
}
public String getThumbnail_pic_s02() {
return thumbnail_pic_s02;
}
public void setThumbnail_pic_s02(String thumbnail_pic_s02) {
this.thumbnail_pic_s02 = thumbnail_pic_s02;
}
public String getThumbnail_pic_s03() {
return thumbnail_pic_s03;
}
public void setThumbnail_pic_s03(String thumbnail_pic_s03) {
this.thumbnail_pic_s03 = thumbnail_pic_s03;
}
}
}
}
接下里,使用rxjava,请求数据(自动返回解析好的数据):
findViewById(R.id.btn_get_news_with_rx_java).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RetrofitUtil.getInstance().getTestService()
.getNewsWithRxJava("8bf17cf1c321723f060d5dc5c4da871a", "top")
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<NewsBean>() {
private Disposable mDisposable;
@Override
public void onSubscribe(Disposable d) {
mDisposable = d;
}
@Override
public void onNext(NewsBean value) {
Toast.makeText(MainActivity.this, value.toString(), Toast.LENGTH_SHORT).show();
mDisposable.dispose();//注销
}
@Override
public void onError(Throwable e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
mDisposable.dispose();//注销
}
@Override
public void onComplete() {
}
});
}
});
运行程序,成功获取请求结果。
撸码暂告一段落,休息下。。。
源码下载地址:https://github.com/shench5612390/Retrofit2WithRxjava2_Demo/tree/master