近几年,Retrofit犹如燎原之火搬席卷了整个Android界。要是不懂Retrofit,简直不好意思出门。。。
由于近几个项目都没用到Retrofit,无奈只能业余时间自己撸一下,写的不好的地方,还请不吝赐教。
要集成retrofit,在app的build.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();
                    }
                });
            }
        });

创建实体类,用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() {

}
                        });

}
        });

浅谈Retrofit2+Rxjava2的更多相关文章

  1. 浅谈 Fragment 生命周期

    版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/Fragment 文中如有纰漏,欢迎大家留言指出. Fragment 是在 Android 3.0 中 ...

  2. 浅谈 LayoutInflater

    浅谈 LayoutInflater 版权声明:本文为博主原创文章,未经博主允许不得转载. 微博:厉圣杰 源码:AndroidDemo/View 文中如有纰漏,欢迎大家留言指出. 在 Android 的 ...

  3. 浅谈Java的throw与throws

    转载:http://blog.csdn.net/luoweifu/article/details/10721543 我进行了一些加工,不是本人原创但比原博主要更完善~ 浅谈Java异常 以前虽然知道一 ...

  4. 浅谈SQL注入风险 - 一个Login拿下Server

    前两天,带着学生们学习了简单的ASP.NET MVC,通过ADO.NET方式连接数据库,实现增删改查. 可能有一部分学生提前预习过,在我写登录SQL的时候,他们鄙视我说:“老师你这SQL有注入,随便都 ...

  5. 浅谈WebService的版本兼容性设计

    在现在大型的项目或者软件开发中,一般都会有很多种终端, PC端比如Winform.WebForm,移动端,比如各种Native客户端(iOS, Android, WP),Html5等,我们要满足以上所 ...

  6. 浅谈angular2+ionic2

    浅谈angular2+ionic2   前言: 不要用angular的语法去写angular2,有人说二者就像Java和JavaScript的区别.   1. 项目所用:angular2+ionic2 ...

  7. iOS开发之浅谈MVVM的架构设计与团队协作

    今天写这篇博客是想达到抛砖引玉的作用,想与大家交流一下思想,相互学习,博文中有不足之处还望大家批评指正.本篇博客的内容沿袭以往博客的风格,也是以干货为主,偶尔扯扯咸蛋(哈哈~不好好工作又开始发表博客啦 ...

  8. Linux特殊符号浅谈

    Linux特殊字符浅谈 我们经常跟键盘上面那些特殊符号比如(?.!.~...)打交道,其实在Linux有其独特的含义,大致可以分为三类:Linux特殊符号.通配符.正则表达式. Linux特殊符号又可 ...

  9. 浅谈Angular的 $q, defer, promise

    浅谈Angular的 $q, defer, promise 时间 2016-01-13 00:28:00  博客园-原创精华区 原文  http://www.cnblogs.com/big-snow/ ...

随机推荐

  1. Typecho 官方文档 接口介绍

    官方开发文档实在是太潦草了 Widget_Archive 接口 参数 描述 indexHandle $archive Widget_Archive对象 $select Typecho_Db_Query ...

  2. Kafka错误“Network is unreachable”和“larger than available brokers”

    确定Kafka安装和启动正确,ZooKeeper可以查到所有的Brokers,但执行: kafka-topics.sh --create --zookeeper localhost:2181 --re ...

  3. Linux入门(1)——Ubuntu16.04安装搜狗拼音

    在网址下载搜狗deb包:http://pinyin.sogou.com/linux/ 将下载的sogoupinyin_2.1.0.0082_amd64.deb放在根目录下. 安装搜狗拼音: ltq@l ...

  4. JQuery设置和去除disabled属性 与 display显示隐藏

    //两种方法设置disabled属性 $('#areaSelect').attr("disabled",true); $('#areaSelect').attr("dis ...

  5. poj2774 sa模版

    学习地址:http://blog.csdn.net/yxuanwkeith/article/details/50636898 #include<iostream> #include< ...

  6. 20155326 2017-2018-1 《信息安全系统设计基础》第2周学习及课堂总结myod

    20155326 2017-2018-1 <信息安全系统设计基础>第1次学习及课堂总结myod 虚拟机之前出了一些问题,然后我重新弄了一个新的虚拟机. 先在虚拟机里面安装了git. 安完以 ...

  7. JavaScript 获取鼠标点击位置坐标

    在一些DOM操作中我们经常会跟元素的位置打交道,鼠标交互式一个经常用到的方面,令人失望的是不同的浏览器下会有不同的结果甚至是有的浏览器下没结果,这篇文章就上鼠标点击位置坐标获取做一些简单的总结,没特殊 ...

  8. js五道经典练习题--第二道仿qq聊天框

    <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>& ...

  9. JQuery Mobile - html5+CSS 禁止IOS长按复制粘贴实现

    因为在移动端APP需要实现长按执行别的事件,但是在IOS系统有默认的长按选择复制粘贴,禁止此功能在网上找了很多资料,最终整理出目前最好的解决方法.实际测试,也并不是很理想,但是可能没有更好办法了! / ...

  10. Weekly Contest 133

    1030. Matrix Cells in Distance Order We are given a matrix with R rows and C columns has cells with ...