Kotlin でアプリ書いてる時にちょっと戸惑った
OkHttpClient のヘッダーの追加は
val httpClient = OkHttpClient.Builder() .addInterceptor { it.proceed(it.request() .newBuilder() .addHeader("Content-Type", "application/json") .build()) } .build()
これを Retrofit で使用する場合
Retrofit.Builder() .baseUrl { HttpUrl.parse(url) } .client(httpClient) .build() .create(HogeHogeApiInterface::class.java, context) .postHuge() ...
Observable 返したい場合や、gson 使いたい場合
ここらへんは java と変わり無いですが
Retrofit.Builder()
.baseUrl { HttpUrl.parse(url) }
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
...
ちなみに HttpLoggingInterceptor 使う場合
val httpClient =
OkHttpClient.Builder()
.addInterceptor {
...
}
.addInterceptor(okhttp3.logging.HttpLoggingInterceptor()
.setLevel(okhttp3.logging.HttpLoggingInterceptor.Level.BASIC))
.build()
実際に使ってるのはここらへんです。
もうちょっと知見が集まってくれると Kotlin 使う人は増えそうな気がする