Kotlin

KotlinでFuelとMoshiを使ってjsonをPOSTする

More than 1 year has passed since last update.

参考

  • moshiを利用して、リクエストをJSON文字列に変換
  • FuelでPOSTする
  val moshi = Moshi.Builder().add(KotlinJsonAdapterFactory()).build()
  val requestAdapter = moshi.adapter(SampleRequest::class.java)

  val header: HashMap<String, String> = hashMapOf("Content-Type" to "application/json")

  val sampleRequest = SampleRequest(
    name = "XXXXX",
    age = 11
  )
  val (_, _, result) = Fuel.post("http://example.com/sample/api").header(header).body(requestAdapter.toJson(sampleRequest)).responseString()

  val (data, _) = result

  println(data)

Gradleの設定 

dependencies {
...
  compile "com.squareup.moshi:moshi:1.5.0"
  compile "com.squareup.moshi:moshi-kotlin:1.5.0"
  compile 'com.github.kittinunf.fuel:fuel:1.11.0'
  compile 'com.github.kittinunf.fuel:fuel-gson:1.11.0'
...
}