ReactiveX 学习笔记(14)使用 RxJava2 + Retrofit2 访问 REST API

JSON : Placeholder

JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。
以下使用 RxJava2 + Retrofit2 访问该网站的 REST API,获取字符串以及 JSON 数据。

  • GET /posts/1
  • GET /posts
  • POST /posts
  • PUT /posts/1
  • DELETE /posts/1

创建工程

打开 Intellij IDEA,File / New / Project...
在 New Project 向导的第1页,选 Gradle,Project SDK 选 1.8,Additional Libraries and Frameworks 选 Java + Kotlin(Java)。
在向导的第2页填上 ArtifactId
在向导的第3页填上选中 use auto-import
在向导的第4页点击 Finish 按钮创建工程

build.gradle 内容如下

plugins {
    id 'java'
    id 'org.jetbrains.kotlin.jvm' version '1.2.60'
}

version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

将 dependencies 这部分的内容改为:

def retrofit_version = '2.4.0'
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    testImplementation group: 'junit', name: 'junit', version: '4.12'
    implementation 'io.reactivex.rxjava2:rxjava:2.1.16'
    implementation 'io.reactivex.rxjava2:rxkotlin:2.2.0'
    implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
    implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
    implementation "com.squareup.retrofit2:converter-gson:$retrofit_version"
    implementation "com.squareup.retrofit2:converter-scalars:$retrofit_version"
}

猜你喜欢

转载自www.cnblogs.com/zwvista/p/9497908.html