HTTP 통신이란?
HTTP(Hypertext Transfer Protocol)은 텍스트 기반의 통신 규약으로 인터넷에서 데이터를 주고받을 수 있는 프로토콜이다.
클라이언트가 HTTP 메시지를 통해 서버에 요청을 보내면, 서버가 요청에 대한 결과를 만들고 이것을 클라이언트가 받는 클라이언트 - 서버 구조이다.
OkHttp 란?
Square 에서 개발한 HTTP 클라이언트 오픈소스 라이브러리로
자바와 코틀린, 안드로이드와 같은 JVM 기반 시스템에서 동작한다.
REST API 및 서버와 HTTP 기반의 클라이언트 요청과 응답에 편의성 제공을 위한 목적으로 개발되었다.
즉, REST API, HTTP 통신을 간편하게 구현할 수 있도록 다양한 기능을 제공해주는 라이브러리다.
Retrofit 이란?
OkHttp와 동일하게 Square 에서 개발한 HTTP 클라이언트 오픈소스 라이브러리다.
Retrofit은 OkHttp를 기반으로 하기 때문에, 내부적으로는 OkHttp를 사용해 HTTP 요청을 처리한다.
그리고 OkHttp의 Interceptor를 사용해 요청 및 응답에 대한 커스터마이징이 가능하다.
Retrofit은 어노테이션을 활용해 간편하게 API 엔드포인트, HTTP 메서드, 요청 및 응답 형식 등을 지정할 수 있다.
@GET, @POST, @Query, @Body, @Part 등..
이를 통해 개발자는 보다 간결하고 유지보수가 쉬운 네트워크 코드를 작성할 수 있다.
OkHttp와 Retrofit 비교
- 공통점
- Square에서 개발한 REST API, HTTP 통신을 위한 오픈소스 라이브러리
- Retrofit은 OkHttp를 기반으로 하기 때문에, 내부적으로는 OkHttp를 사용해서 HTTP 요청을 함
- 따라서 근본적인 HTTP 통신 구조는 동일함
- 차이점
- 추상화 레벨
- OkHttp는 낮은 수준의 라이브러리로 HTTP 요청과 응답을 생성하고 처리하는 것이 비교적 복잡할 수 있음
- Retrofit은 높은 수준의 추상화를 제공하며, 어노테이션을 사용해 API 엔드포인트를 인터페이스로 정의할 수 있음
- Response Handling
- OkHttp
- 응답을 직접 처리해야하며, JSON 파싱 등의 작업도 수동으로 해야 할 수 있음
- enqueue를 사용하면 네트워크 호출이 자동으로 백그라운드에서 수행되지만, Thread 변경 기능이 제공되지 않기 때문에 메인 스레드에서 데이터를 업데이트 하기 위해선 runOnUiThread를 사용해야 함
- Retrofit
- GSON, Moshi 등의 라이브러리와 쉽게 통합할 수 있어 자동으로 JSON을 자바, 코틀린 객체로 변환해줌
- enqueue를 사용하면 네트워크 호출이 백그라운드에서 이루어지며, 자동으로 메인스레드에 전달됨
- OkHttp
- 추상화 레벨
Retrofit 의 특징
- Type safe
- 자바나 코틀린의 인터페이스와 어노테이션을 사용해 API를 정의하기 때문에 컴파일 시간에 오류를 잡을 수 있다
- 비동기 및 동기 지원 요청
- RxJava, Coroutine 과 같은 도구를 사용해 비동기 처리를 쉽게 할 수 있음
- 자동 JSON 파싱
- GSON, Moshi 등 다양한 JSON 라이브러리와 연동이 가능하다
- 코드 최적화
- 어노테이션을 사용해 인터페이스를 작성하기 때문에 API 호출 코드가 매우 간결하고 가독성이 높음
실제 예제를 보면 이해가 더 빠를 것이다
OkHttp 예제
동기 Get
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("https://publicobject.com/helloworld.txt")
.build()
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) throw IOException("Unexpected code $response")
for ((name, value) in response.headers) {
println("$name: $value")
}
println(response.body!!.string())
}
}
비동기 Get 예제
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("http://publicobject.com/helloworld.txt")
.build()
client.newCall(request).enqueue(object : Callback { // 비동기로 실행하기 위해 enqueue 사용
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
for ((name, value) in response.headers) {
println("$name: $value")
}
println(response.body!!.string())
}
}
})
}
Retrofit 예제
자바 예제
// 인터페이스 정의
public interface GitHubService {
@GET("users/{user}/repos")
Call<List<Repo>> listRepos(@Path("user") String user);
}
// GitHubService 인터페이스 구현 생성
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
GitHubService service = retrofit.create(GitHubService.class);
// 동기 또는 비동기 HTTP 요청 가능
Call<List<Repo>> repos = service.listRepos("octocat");
Converter
Retrofit은 JSON을 자동으로 자바, 코틀린 객체로 변환하는 기능을 제공한다.
addConverterFactory()에 컨버터를 넣으면 된다.
// Gson 사용
val retrofit = Retrofit.Builder()
.baseUrl("https://example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
// Moshi 사용
val retrofit = Retrofit.Builder()
.baseUrl("https://example.com/")
.addConverterFactory(MoshiConverterFactory.create())
.build()
Interceptor
인터셉터를 통해 요청과 응답의 중간에 원하는 로직을 추가할 수 있다
val client = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.HEADERS
})
.build()
val retrofit = Retrofit.Builder()
.baseUrl("https://example.com/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
참고
Retrofit, OkHttp 관련
Android 네트워크 통신 라이브러리(OkHttp, Retrofit)
Android Server 통신 라이브러리
velog.io
OkHttp 예제
https://square.github.io/okhttp/
Overview - OkHttp
OkHttp HTTP is the way modern applications network. It’s how we exchange data & media. Doing HTTP efficiently makes your stuff load faster and saves bandwidth. OkHttp is an HTTP client that’s efficient by default: HTTP/2 support allows all requests to
square.github.io
Retrofit 예제
https://square.github.io/retrofit/
Retrofit
A type-safe HTTP client for Android and Java
square.github.io
converter, interceptor
https://velog.io/@ouowinnie/%EA%B0%9C%EB%85%90-%EB%A0%88%ED%8A%B8%EB%A1%9C%ED%95%8F-Retrofit
'Native App > 👽Android' 카테고리의 다른 글
Fragment (0) | 2024.08.24 |
---|---|
Intent란 (0) | 2024.08.05 |
Context란 (0) | 2024.07.29 |
Kotlin을 사용하는 이유 (0) | 2024.07.26 |
Android 4대 컴포넌트 (0) | 2024.07.26 |
댓글