很多人对于现在的网络请求需求都非常不一样,下面我给大家介绍一种网络请求的一种方式:OKHttp+ RxJava
OKHttp本身就是用来请求网络数据的,前面封装的OK处理异步用的是Handler对象,这篇文章就是将Handler替换成了最近使用的一种处理异步的框架RxJava
具体使用
1.添加依赖
RxJava的依赖:
compile 'io.reactivex:rxjava:1.0.14'
compile 'io.reactivex:rxandroid:1.0.1'
OKHttp的依赖:
compile 'com.squareup.okhttp3:okhttp:3.9.0'
解析数据使用的gson依赖:
compile 'com.google.code.gson:gson:2.2.4'
2.添加权限
<uses-permission android:name="android.permission.INTERNET"/>
3.实现代码:
MainActivity的xml文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="liuhao.baway.com.retrofit_demo.MainActivity">
<TextView
android:id="@+id/textview"
android:layout_centerInParent="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="显示获取的数据" />
</RelativeLayout>
MainActivity页面的实现逻辑:
import android.os.Bun