使用Retrofit和RxJava整合访问网络,然后将数据显示到界面上

def retrofitVersion = '2.0.0-beta1'dependencies {compile fileTree(dir: 'libs', include: ['*.jar'])testCompile 'junit:junit:4.12'compile 'com.android.support:appcompat-v7:22.2.1'compile 'com.android.support:design:22.2.1'//Retrofitcompile "com.squareup.retrofit:retrofit:$retrofitVersion"compile "com.squareup.retrofit:converter-gson:$retrofitVersion"//RxJavacompile 'io.reactivex:rxjava:1.0.14'compile 'io.reactivex:rxandroid:1.0.1'
}

在app.buidle里面添加ReTrofit和RxJava的依赖,在

dependencies上面一定要注明Retrofit的版本号
def retrofitVersion = '2.0.0-beta1'

MainActivity里面的代码:
public class MainActivity extends Activity implements View.OnClickListener {/*** 自定义的观察者*/public MyObserver observer;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Button btn = (Button) findViewById(R.id.btn);btn.setOnClickListener(this);observer = new MyObserver();//创建一个观察者
}//点击按钮就请求网络
    @Overridepublic void onClick(View view) {if (view.getId() == R.id.btn) {//点击获取好友动态Control control = new Control(this);control.getFriendsShareFromServer();//访问网络并且解析Json}}/*** 自定义的观察者*/class MyObserver implements rx.Observer<Resquest_friends_info> {@Overridepublic void onCompleted() {Log.d("msg", "观察的事件结束了---");}@Overridepublic void onError(Throwable e) {Log.d("msg", "观察的事件出错了");}//订阅观察者后,被观察者会把数据传回来@Overridepublic void onNext(Resquest_friends_info resquest_friends_info) {Log.d("msg", "观察者OnNext");ArrayList<Resquest_friends_info.EveryShareInfo> results = resquest_friends_info.getResult();Toast.makeText(MainActivity.this,"观察者收到了数据",Toast.LENGTH_SHORT).show();for (Resquest_friends_info.EveryShareInfo info : results) {//每条分享的信息Log.d("msg", "分享信息++++" + info.getPub_context() + "--->" + info.getPub_datetime() + "----->" + info.getPub_frd_name());Log.d("msg", "-----------------------------------------------------");for (Resquest_friends_info.EveryShareInfo.Reply reply : info.pub_com) {//每条回复Log.d("msg", "评论+++++" + reply.getPc_name() + "--->" + reply.getPc_txt() + "--->");Log.d("msg", "----------------------------------------------------------------");}for (Resquest_friends_info.EveryShareInfo.Thumb thumb : info.pub_thumup) {//每个点赞Log.d("msg", "点赞++++" + thumb.getPt_name());Log.d("msg", "---------------------------------------");}}}}
}

Resquest_friends_info表示一个JavaBean对象,app结构如下:
//访问网络的接口
public interface GitHubService {
//    ================================================  =   =   ==  ==========//  //表示Get请求,里面是地址这是写死的地址,但是地址中的参数要动态改变,就不能这样写//  @GET("/index.php?m=home&c=message&a=resquest_friends_info&uid=1234567&p=1")    
//参数要动态传进去,所以要这样写//@GET(value = "/index.php"),  或者@GET("/index.php")也可以
@GET("/index.php")
//用这个方法去访问网络
Call<Resquest_friends_info> getFriendsShareInfo(@Query("m") String m,@Query("c") String c,@Query("a") String a,@Query("uid") String uid,@Query("p") String p); 
}

这里的路径可以自己修改,比如,写成这样也是可以的:
//@GET("/index.php?m=home")//Call<Resquest_friends_info> getFriendsShareInfo(@Query("c") String c,@Query("a") String a,@Query("uid") String uid,@Query("p") String p);
 

/**此类是访问网络的Control* Created by xhj on 15-12-18.*/
public class Control {public static final String TAG="msg";  //URL根路径,一般就是域名public static final String APITrack="http://192.168.1.102";private MainActivity activity;/**构造方法时把观察者所在的类传进来*/public Control(MainActivity activity){this.activity=activity;}/**从服务器获取好友动态*/public void getFriendsShareFromServer(){Retrofit retrofit = new Retrofit.Builder().baseUrl(APITrack).addConverterFactory(GsonConverterFactory.create())//用Gson去解析数据.build();GitHubService git = retrofit.create(GitHubService.class);Call<Resquest_friends_info> call = git.getFriendsShareInfo();call.enqueue(new Callback<Resquest_friends_info>() {        //访问网络回来,并且成功拿到数据就调用这个方法@Overridepublic void onResponse(Response<Resquest_friends_info> response) {final Resquest_friends_info resquest_friends_info = response.body();Observable<Resquest_friends_info> observable = Observable.create(new Observable.OnSubscribe<Resquest_friends_info>() {@Overridepublic void call(Subscriber<? super Resquest_friends_info> subscriber) {subscriber.onNext(resquest_friends_info);subscriber.onCompleted();//事件结束
                    }});observable.subscribe(activity.observer);//订阅观察者
}@Overridepublic void onFailure(Throwable t) {Log.d("msg","失败了");}});}
}


转载于:https://www.cnblogs.com/android-yus/p/5062724.html

使用Retrofit和RxJava相关推荐

  1. java中使用okhttpsoap,Android okHttp网络请求之Retrofit+Okhttp+RxJava组合

    Retrofit介绍: Retrofit和okHttp师出同门,也是Square的开源库,它是一个类型安全的网络请求库,Retrofit简化了网络请求流程,基于OkHtttp做了封装,解耦的更彻底:比 ...

  2. Retrofit与RXJava整合

    Retrofit 除了提供了传统的 Callback 形式的 API,还有 RxJava 版本的 Observable 形式 API.下面我用对比的方式来介绍 Retrofit 的 RxJava 版 ...

  3. retrofit与rxjava使用

    retrofit和rxjava(加深) http://www.jianshu.com/p/64af68c5638c Android Retrofit + RxJava使用详解(基础) http://w ...

  4. Java游戏碟中谍,煮 Retrofit 论 RxJava(一)

    首先,本篇是基于这个的总结.思考和拓展,那篇作者由浅入深,徐徐道来,读起来感觉很棒. ** 1.使用Retrofit来进行网络请求 ** a.网络接口使用豆瓣电影的top250,我们根据它返回的jso ...

  5. Retrofit+OKHttp+RxJava的使用

    什么是响应式编程   响应式编程是一种基于异步数据 流概念的编程模式.数据流就像一条河:它可以被观测,被过滤,被操作,或者为新的消费者与另外一 条流合并为一条新的流. 什么是RxJava RxJava ...

  6. 解决Retrofit和RxJava 抛出异常报错问题

    解决Retrofit和RxJava 抛出异常报错问题 package com.dingtao.rrmmp.core.exception;public class ApiException extend ...

  7. Android Retrofit使用教程(三):Retrofit与RxJava初相逢

    上一篇文章讲述了Retrofit的基本使用,包括GET,POST等请求.今天的文章中Retrofit要与RxJava配合使用. 了解RxJava RxJava有种种好处,我不在这里一一讲述.这里我只给 ...

  8. java okhttp3 工具类,Retrofit+okhttp+Rxjava网络请求工具类

    1.BaseApis接口封装请求方式 package com.example.wdshop.network; import java.util.Map; import okhttp3.Response ...

  9. ACCU天气API以及Okhttp、Retrofit、RxJava的使用

    因为公司项目需要使用到天气信息,而且有国外的使用需求,所以就没有选择国内的信息提供商,而是把目光瞄向了国际化的 ACCUWeather.通过下面的两个链接,我们可以简单的了解到AccuWeather的 ...

最新文章

  1. websocket客户端
  2. 【PAT (Advanced Level) Practice】1086 Tree Traversals Again (25 分)
  3. 《Java核心技术 卷Ⅱ 高级特性(原书第10版)》一导读
  4. dev c++怎么调试_「正点原子NANO STM32开发板资料连载」第十八章 USMART 调试组件...
  5. IdentityServer4之持久化很顺手的事
  6. linux的启动流程和加载程序
  7. 组了个视频号的局,汇报下数据!
  8. net根据list创建xml_#一起学spring#创建多模块项目
  9. 那些让程序员炸毛的奇葩需求,说起来满满的都是泪!
  10. java大小端在线转换_Java 大小端转换
  11. MATLAB 常见取整函数
  12. IDEA软件中的五子棋~
  13. 微信小程序码获取-从频繁失败到成功率100%
  14. linux下的定时任务
  15. 单机游戏数据库探讨(MySQL嵌入式服务器的使用)(未完)
  16. LLVM 编译器学习笔记之三 -- TableGen语言编写*.td文件
  17. 设计师必备!免费下载 PSD 素材的32个网站
  18. 一种万能解锁的解决方法
  19. 线程池2nd卷:虎落平阳被犬欺
  20. 网络复现之基于TPS的STN网络

热门文章

  1. Ubuntu Server搭建FTP服务器(2) --本地用户FTP服务器架设
  2. MySQL动态行转列
  3. hive与hbase的以及mongodb和cassandra区别整理
  4. NMS(Non-Maximum Suppression)非极大值抑制
  5. html th不显示下边框,css怎么设置不显示table的边框?
  6. redhat6.4安装nginx
  7. Linux内核线程kernel thread详解--Linux进程的管理与调度(十)【转】
  8. Java 创建、填充PDF表单域
  9. Log4cpp介绍及使用
  10. 使用django创建一个单表查询的图书管理系统