5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

kotlin + retrofit2 + MoshiでAPIアクセス

Last updated at Posted at 2017-07-07

kotlinでretrofit2を使ってAPIアクセスする処理を書いてみたのでメモ。
今回はjsonパーサにMoshiを使ってみました。

app/build.gradle
dependencies {
    //...

    def retrofit_version = '2.3.0'
    compile "com.squareup.retrofit2:retrofit:$retrofit_version"
    compile "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
    compile "com.squareup.retrofit2:converter-moshi:$retrofit_version"

    def moshi_version = '1.5.0'
    compile "com.squareup.moshi:moshi:$moshi_version"
    compile "com.squareup.moshi:moshi-kotlin:$moshi_version"

    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
}
TestService.kt
object TestService {
    fun test() {
        val retrofit = Retrofit.Builder()
                .baseUrl("http://www.xxx.com")
                .addConverterFactory(MoshiConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
        val testClient = retrofit.create(TestClient::class.java)

        selfClient.getSomething()
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe ({
                    val user = it
                    print(user)
                })


    }
}
interface SelfClient {
    @GET("/test")
    fun authenticate(@Header("Authenticate") authenticate: String): Observable<TestDto>
}

だいたいこんな感じで取得できます。

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?