안드로이드

[Android] okHttp3란?

빡수수 2024. 6. 25. 20:21

서론

okHttp는 Square에서 개발한 java 및 android 용 HTTP 클라이언트 라이브러리이다. 위 라이브러리를 활용하면 HTTP 통신을 쉽고 효율적으로 처리할 수 있다. API 통신 시 Retrofit2와 결합하여 자주 사용되는데 okHttp에 대한 내용을 간단하게 정리해보려 한다.


주요 기능

  •  비동기 요청 지원 : okHttp3는 비동기 요청을 지원하여 네트워크 통신 중 UI 스레드를 블로킹하지 않음
  • 커넥션 풀링(Connection Pooling): HTTP/1.1의 Keep-Alive 기능과 HTTP/2의 멀티 플렉싱을 통해 효율적인 커넥션 풀링을 지원한다. 이는 네트워크 사용을 최적화하고 성능을 향상함
  • 투명한 GZIP 압축: 응답 본문을 자동으로 GZIP 압축 해제하여 네트워크 트래픽을 줄인다.
  • 응답 캐싱(Response Caching): 로컬 캐싱을 통해 동일한 요청에 대한 네트워크 트래픽을 최소화한다.
  • 인터셉터(Interceptors: 요청과 응답을 가로채고 수정할 수 있는 인터셉터를 제공하여, 로깅, 인증, 리트라이 등의 작업을 쉽게 처리할 수 있다.
  • WebSocket 지원: HTTP와 함께 WebSocket을 지원하여 실시간 통신을 처리할 수 있다.

 

기본 사용법

의존성 추가

dependencies {
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}

 

동기식 HTTP 요청 및 응답처리 sample

val client = OkHttpClient()

val request = Request.Builder()
    .url("https://example.com")
    .build()

client.newCall(request).execute().use { response ->
    if (!response.isSuccessful) throw IOException("Unexpected code $response")

    println(response.body!!.string())
}

 

비동기 요청 및 응답처리 sample

val client = OkHttpClient()

val request = Request.Builder()
    .url("https://example.com")
    .build()

client.newCall(request).enqueue(object : Callback {
    override fun onFailure(call: Call, e: IOException) {
        e.printStackTrace()
    }

    override fun onResponse(call: Call, response: Response) {
        response.use {
            if (!it.isSuccessful) throw IOException("Unexpected code $response")

            println(it.body!!.string())
        }
    }
})

 


 

Retrofit2과의 통합

OkHttp3는 종종 Retrofit2와 함께 사용된다. Retrofit2는 고수준의 REST API 클라이언트를 제공하고, OkHttp3는 저수준의 HTTP 클라이언트로서 네트워크 요청을 실제로 처리한다. 이 결합은 네트워크 요청을 쉽게 처리할 수 있도록 도와준다.

 

기본 사용법

의존성 추가

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.okhttp3:okhttp:4.9.3'
}

 

API 인터페이스 정의

interface ApiService {
    @GET("users/{user}")
    fun getUser(@Path("user") userId: String): Call<User>
}

 

Retrofit 인스턴스 생성

val okHttpClient = OkHttpClient.Builder()
    .addInterceptor(HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    })
    .build()

val retrofit = Retrofit.Builder()
    .baseUrl("https://api.example.com/")
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttpClient)
    .build()

val apiService = retrofit.create(ApiService::class.java)

 

API 호출

val call = apiService.getUser("123")
call.enqueue(object : Callback<User> {
    override fun onResponse(call: Call<User>, response: Response<User>) {
        if (response.isSuccessful) {
            val user = response.body()
            // 사용자 정보 처리
        }
    }

    override fun onFailure(call: Call<User>, t: Throwable) {
        t.printStackTrace()
    }
})

 


마치며

OkHttp3는 성능이 뛰어나고 사용이 간편한 HTTP 클라이언트 라이브러리로, Java 및 Android 환경에서 HTTP 통신이 필요한 경우 매우 유용하다. Retrofit2와 함께 사용하면 더욱 강력한 네트워크 기능을 쉽게 구현할 수 있고, 실제로 함께 사용되는 경우가 많으니 꼭 알아두자👍