(kotlin) retrofit

박용석·2023년 9월 20일
0

retrofit

안드로이드 앱에서 네트워크 통신을 쉽게 처리하기 위한 라이브러리 중 하나로, RESTful API와 데이터를 주고받는 데 사용된다.

  1. Retrofit과 LiveData를 사용하기위해 필요한 라이브러리를 의존성에 추가해준다.
implementation 'androidx.lifecycle:lifecycle-viewmodel:2.x.x'
implementation 'androidx.lifecycle:lifecycle-livedata:2.x.x'
implementation 'androidx.lifecycle:lifecycle-extensions:2.x.x'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // JSON 데이터를 파싱하기 위한 Gson 컨버터
  1. 인터넷을 사용하기 위해 manifest파일에 인터넷 사용권한을 추가해준다.
<uses-permission android:name="android.permission.INTERNET"/>
  1. Retrofit을 사용하기 위한 데이터 모델 클래스를 생성한다. (JSON 응답의 구조와 일치하는 kotlin 데이터 클래스 정의)
data class Post(
	@Serialized("userId") // JSON 객체와 해당 변수를 매칭할 때 사용
    val userId: Int,
    val id: Int,
    val title: String,
    val body: String
)
  1. Retrofit 인터페이스를 생성한다. 이 인터페이스는 서버의 엔드포인트와 요청 메서드를 정의한다.
import retrofit2.Call
import retrofit2.http.GET

interface JsonPlaceholderService {
    @GET("/posts/1") // API 엔드포인트 설정
    fun getPost(): Call<Post> // GET 요청을 위한 메서드
}
  1. Retrofit 객체를 초기화하고 사용한다. 일반적으로 앱의 'Application' 클래스 또는 다른 적절한 위치에서 Retrofit 객체를 초기화 한다.
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

val retrofit = Retrofit.Builder()
    .baseUrl("https://jsonplaceholder.typicode.com") // API의 기본 URL 설정
    .addConverterFactory(GsonConverterFactory.create()) // Gson 컨버터 사용
    .build()

val service = retrofit.create(JsonPlaceholderService::class.java) // Retrofit 서비스 생성
  1. ViewModel 클래스를 생성하여 네트워크 요청과 데이터 관리를 담당한다.
import androidx.lifecycle.ViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class PostViewModel : ViewModel() {
    private val _postLiveData = MutableLiveData<Post>()
    val postLiveData: LiveData<Post> = _postLiveData

    private val jsonPlaceholderService = RetrofitInstance.create(JsonPlaceholderService::class.java)

    fun fetchPost() {
        val call = jsonPlaceholderService.getPost()
        call.enqueue(object : Callback<Post> {
            override fun onResponse(call: Call<Post>, response: Response<Post>) {
                if (response.isSuccessful) {
                    val post = response.body()
                    _postLiveData.value = post
                } else {
                    // 오류 처리
                }
            }

            override fun onFailure(call: Call<Post>, t: Throwable) {
                // 네트워크 오류 처리
            }
        })
    }
}
  1. 이제 Retrofit을 사용하여 네트워크 요청을 수행할 수 있다. 이를 통해 서버에서 데이터를 가져올 수 있다.
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.Observer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: PostViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // ViewModel 초기화
        viewModel = ViewModelProvider(this).get(PostViewModel::class.java)

        // LiveData 관찰
        viewModel.postLiveData.observe(this, Observer { post ->
            if (post != null) {
                // 데이터 업데이트 발생 시 실행될 코드
                // post를 사용하여 UI 업데이트 또는 다른 작업 수행
            }
        })

        // 네트워크 요청 시작
        viewModel.fetchPost()
    }
}

Retrofit을 통해 데이터를 보내거나 받을 때 보다 복잡한 시나리오에 대한 처리를 추가로 구현할 수 있다. 또한 보안 및 예외 처리 등을 고려하여 실제 앱에서 사용할 때 적절한 보안 및 오류 처리를 구현해야 한다.

profile
슬기로운 개발 활동

0개의 댓글