所有的代码都写在一个文件内了
代码中所导入的包,请务必注意不要导错了,不然运行会导致报错
代码如下:
import retrofit2.Call
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Query
import rx.Observable
import rx.schedulers.Schedulers
/**
* ====================================
* 作者:Jerry
* 创建日期:2017/6/25 19:41
* 描述:
* ====================================
*/
/**
* Retrofit 请求
*/
interface IService {
@GET("/repos/vmg/redcarpet/stargazers")
fun getStarGazers(): Call<List<User>>
@GET("/repos/vmg/redcarpet/issues")
fun getIssues(@Query("state") state: String): Call<List<User2>>
@GET("/repos/AndroidJerry8/SoulMate")
fun getSoulMate(): Observable<Response<SoulMate>>
}
class Service {
companion object {
val service: IService by lazy(LazyThreadSafetyMode.NONE) {
Retrofit.Builder()
.baseUrl("https://api.github.com")
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(IService::class.java)
}
}
}
fun main(args: Array<String>) {
val service = Service.service
service.getStarGazers().execute().body().map(::println)
service.getIssues("open").execute().body().map(::println)
//Java 中
service.getSoulMate().subscribe({ result -> obtain(result) }, { t -> println(t.message) })
//Android 中
service.getSoulMate()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ result -> obtain(result) }, { t -> println(t.message) })
}
fun obtain(response: Response<SoulMate>) {
println("成功")
if (response.isSuccessful)
println(response.body())
else
println(response.errorBody().string())
}