안드로이드개발

Retrofit2으로 API 서버와 통신

아뵹젼 2022. 1. 2.

처음에 무작정 안드로이드 개발을 할 때에는 직접 HTTP 통신을 위한 클래스를 작정하느라 하루종일 애를 썼던 기억이 있다.

역시 독학이 답은 아닌 것으로,,,,

아무튼 Retrofit 은 네트워크로 부터 전달된 데이터를 필요한 형태의 객체로 받을 수 있는 Http client 라이브러리 이다.

Retrofit 을 사용하면 연결, 오류처리, 재시도 등을 직접 구현하지 않고 편리하게 처리할 수 있다.

 

 

1) Interface 

package com.example.flo

import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST

interface AuthRetrofitInterface {
    @POST("/users")
    fun signUp(@Body user: User): Call<AuthResponse>

    @POST("/users/login")
    fun login(@Body user: User): Call<AuthResponse>
}

우리가 요청할 동작, 즉 API 의 명세를 인터페이스에 적어두면 된다.

반환값은 Call<> 로 , AuthResponse 가 반환타입임을 알 수 있다.

@POST( ) 에서 괄호안의 주소는 baseUrl 뒤에 붙을 디렉토리이다.

 

 

2. 반환값 지정 클래스

package com.example.flo

import com.google.gson.annotations.SerializedName

// SerializedName 으로 직접 key 값 정해줄 수 있음
data class Auth(@SerializedName("userIdx")val userIdx: Int, @SerializedName("jwt") val jwt: String)
data class AuthResponse(
    @SerializedName("isSuccess") val isSuccess: Boolean,
    @SerializedName("code")val code:Int,
    @SerializedName("message")val message : String,
    @SerializedName("result")val result:Auth?
    )

  반환값은 다음과 같은 클래스로 지정해두었다.

@SerializedName 은 데이터 클래스가 JSON 문자열 형식으로 변환되는 것으로, 반환값과 Json 을 지정한 key 값을 통해 매칭시킬 수 있다.

 

 

3. Retrofit 

class AuthService {
  private lateinit var signUpView: SignUpView

  fun setSignUpView(signUpView: SignUpView){
          this.signUpView = signUpView
      }

  fun signUp(user:User){
      val authService = getRetrofit().create(AuthRetrofitInterface::class.java)

      signUpView.onSignUpLoading()

      authService.signUp(user).enqueue(object : Callback<AuthResponse> {
          override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
              Log.d("SIGNUPACT/API-RESPONSE", response.toString())

              val resp = response.body()!!
              Log.d("SIGNUPACT/API-RESPONSE-FLO", resp.toString())
              when(resp.code){
                  1000 -> {
                      signUpView.onSignUpSuccess()
                  }
                  else-> signUpView.onSignUpFailure(resp.code, resp.message)
              }
          }

          override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
              Log.d("SIGNUPACT/API-RESPONSE", t.message.toString())
              signUpView.onSignUpFailure(400, "네트워크 오류가 발생했습니다.")
          }
      })
  }



     private fun getRetrofit(): Retrofit {
          val baseUrl ="서버 URL"
          return Retrofit.Builder()
              .baseUrl(baseUrl)
              .addConverterFactory(GsonConverterFactory.create()) .build()
      }

 회원가입을 위한 Retrofit 객체를 생성하고, 인터페이스에 적어둔 함수 signUp 를 구현하면 된다.

enqueue 를 통해 큐에 데이터를 집어넣은 후, 통신 결과가 성공적으로 응답하면 onResponse내부가 실행되며, 실패하면 onFailure가 실행 된다.

 

 

여기서 signUpView 는 회원가입이 로딩되는 중, 성공되었을 때, 실패했을 때의 함수를 구현하기 위한 인터페이스이다.

package com.example.flo

interface SignUpView {
    fun onSignUpLoading()
    fun onSignUpSuccess()
    fun onSignUpFailure(code: Int, message: String)
}

 

 

4. 실행

val authService = AuthService()
authService.setSignUpView(this)
authService.signUp(getUser())

위에서 생성한 Retrofit 관리 클래스 객체를 생성하고, 실행하면 Http 통신부터 실패 혹은 성공의 반환값을 알려준다.

 

 

 

 

댓글