LoginSignup
6
1

More than 5 years have passed since last update.

Retrofit2でtext/plainレスポンスな定義を作る

Posted at

ナニコレ

Retrofitでまさかのtext/plainなレスポンスのAPIを叩けと言われたのでその対処法をまとめます
自分のメモ用です。

使うの?

しっ

GsonConverterFactory + RxJava2CallAdapterFactory

ココらへんは好みでいいと思いますが、今回JSONパーサーは GsonConverterFactory
データのコールバックで RxのSingleを使いたかったので RxJava2CallAdapterFactory を利用しました。

app/build.gradle
implementation "com.squareup.retrofit2:retrofit:$retrofit_version"
implementation "com.squareup.retrofit2:adapter-rxjava2:$retrofit_version"
implementation 'com.squareup.retrofit2:converter-gson:$retrofit_version'
ApiClientFactory.kt
val builder = Retrofit.Builder()
                .baseUrl("https://hogehoge/gefungefun/")
                .client(httpClient)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

return builder.build().create(ApiClientInterface::class.java)
ApiClientInterface.kt
interface ApiClientInterface {
    @POST("apiUrl")
    fun updateData(): Single<String>
}
Repository.kt
fun update(): Single<String> = apiClient.updateData().subscribeOn(Schedulers.newThread())

こんな感じで定義しときましょう。

ScalarsConverterFactory の追加

今回のミソ。 ScalarsConverterFactory さんです
この人を追加してあげると、単純なStringのデータとしてレスポンスを扱ってくれます。

app/build.gradle
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" // 追加
ApiClientFactory.kt
val builder = Retrofit.Builder()
                .baseUrl("https://hogehoge/gefungefun/")
                .client(httpClient)
                .addConverterFactory(ScalarsConverterFactory.create())  // 追加
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())

        return builder.build().create(ApiClientInterface::class.java)

これだけで、Repository#update の subscribe:onNext ではただの String としてデータが扱えます。

6
1
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
6
1