build.gradle
build.gradleのdependenciesに以下を追加してください
compile 'com.squareup.okhttp3:okhttp:3.9.0' compile group: 'org.json', name: 'json', version: '20170516'
Test.kt
以下のような感じでコードを書くと結果を受け取れます. 別途Nullチェックはするべきっぽいです.
import okhttp3.MediaType import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import org.json.JSONObject class Test(){ fun post(): String?{ val url = "url" val client: OkHttpClient = OkHttpClient.Builder().build() // create json val json = JSONObject() json.put("name", "mituba") json.put("hobby", "programming") // post val postBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString()) val request: Request = Request.Builder().url(url).post(postBody).build() val response = client.newCall(request).execute() // getResult val result: String? = response.body()?.string() response.close() return result } }
非常に簡単にPOSTすることができました.