OkHttp๋ Square, Inc.๋ผ๋ ํ์ฌ์์ ๊ฐ๋ฐ๋์์ต๋๋ค.
OkHttp๋ Square, Inc.์ ๊ฐ๋ฐ์๋ค์ด ๋ง๋ ๊ณ ์ฑ๋ฅ HTTP ํด๋ผ์ด์ธํธ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก, ์๋๋ก์ด๋ ๋ฐ ์๋ฐ ์ ํ๋ฆฌ์ผ์ด์
์์ ๋คํธ์ํฌ ํต์ ์ ์ฒ๋ฆฌํ๋ ๋ฐ ์ฌ์ฉ๋ฉ๋๋ค.
dependencies {
implementation 'com.squareup.okhttp3:okhttp:4.9.2'
}
class OkhttpGetApiCall(
private val okhttpClient: OkHttpClient = OkHttpClient()
) {
private val getRequest = okhttp3.Request.Builder()
.url("https://gorest.co.in/public/v2/users")
.get()
.header("content-type", "application/json")
.build()
fun get(): ResponseBody = okhttpClient.newCall(getRequest)
.execute()
.peekBody(Long.MAX_VALUE)
fun getAsync(): Unit = okhttpClient.newCall(getRequest)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) = println("Failed to execute request")
override fun onResponse(call: Call, response: Response) = println("Response received ${response.body?.string()}")
})
}
class OkhttpPostApiCall(
private val okhttpClient: OkHttpClient = OkHttpClient(),
) {
private val postRequest = okhttp3.Request.Builder()
.url("https://gorest.co.in/public/v2/users")
.post(FormBody.Builder() // patch put delete ...
.add("name","junny")
.add("email","junny@mail.com")
.add("gender","junny")
.build()
)
.header("content-type", "application/json")
.build()
fun post(): ResponseBody = okhttpClient.newCall(postRequest)
.execute()
.peekBody(Long.MAX_VALUE)
fun postAsync(): Unit = okhttpClient.newCall(postRequest)
.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) = println("Failed to execute request")
override fun onResponse(call: Call, response: Response) = println("Response received ${response.body?.string()}")
})
}