[kotlin] 회원가입

이미리·2022년 6월 28일
0

[kotlin] Android

목록 보기
2/5

1. 환경설정

add retrofit2

// Retrofit
    implementation "com.squareup.retrofit2:retrofit:2.9.0"
    implementation "com.squareup.retrofit2:converter-gson:2.9.0"
    implementation "com.squareup.retrofit2:adapter-rxjava2:2.9.0"

gradle 파일에 위의 라이브러리들을 import시켜준다.

permission.internet

인터넷 사용을 위해서는 manifests 파일에 인터넷 사용을 허가해주는 코드를 추가해주어야 한다.

<uses-permission android:name="android.permission.INTERNET"

2. API 명세서

api 명세서에 명시되어있는 request로 보내줄 때 json의 형태로 변형해서 보내준다.

json으로 request를 보내줄 때에는 @SerializedName(value = "email") val email: String의 형태로 만들어주어야 한다.

@SerializedName annotation이 java 객체를 JSON 형태로 자동 변환해준다.

3. Retrofit

retrofit 공식 문서를 보면서 진행.

1. interface


인터페이스에 들어갈 정보 :
method, url을 표시해주어야함. & 어떤 method를 실행시킬 것인지 표시해주어야 한다.

AuthRetrofitInterface를 생성해주어 작성하겠다.

package com.example.flo.data.remote

import com.example.flo.data.entities.User
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>
}

이때 Call<>의 괄호 안에 들어가는 값은 우리가 reponse 받을 값의 데이터클래스 형태로 정의된 것이다.
회원가입 요청 시 "isSuccess", "code", "message" 값을 리턴받으므로 이 형태의 데이터 클래스를 만들어준다. 위의 코드에서는 데이터 클래스의 이름을 AuthResponse로 명시했기 때문에 그대로 만들어준다.

data class AuthResponse(val isSuccess:Boolean, val code:Int, val message:String)

2. retrofit 객체 생성

baseurl을 넣기 & retrofit.create 함수를 이용해서 api의 형식에 맞게 작성한 retrofit 객체를 생성함.

NetworkModule

com.example.dologinout

import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

const val BASE_URL = "https://base-url.com"

fun getRetrofit(): Retrofit {
    val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create()).build()

    return retrofit
}

addConverterFactory(GsonConverterFactory.create()를 통해 json으로 통신할 수 있도록 convert해준다.

리턴값으로 retrofit 객체를 지정해준다.

signUp() 함수에서 retrofit 객체를 create 함수를 통해 생성해서 이용해준다.

3. Create retrofit obj in signUp() fuc

val authService = getRetrofit().create(AuthRetrofitInterface::class.java)
위의 코드를 통해서 authService라는 AuthRetrofitInterface 객체를 생성해준다.
-> AuthRetrofitInterface 모양을 갖춘 retrofit 객체를 생성한다고 보면 될까?

authService.signUp(getUser()).enqueue(object: Callback<AuthResponse>{
            override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
                TODO("Not yet implemented")
            }

            override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
                TODO("Not yet implemented")
            }
        })

signUp()를 통해서 받아온 AuthResponse 데이터 클래스를 enqueue push back을 통해 넣어준다.
이때 제대로 통신되어 응답이 왔을 때 이를 처리해주는 onResponse()와 네트워크 연결이 실패했을 때 실행되는 onFailure()가 있다.

서버 개발자가 응답한 값을 파싱하기 위해서는 response: Response의 body 값을 가져와야한다.

* POST는 Body에 전송할 데이터를 담아 서버에 생성합니다. @Body를 이용해 HTTP 요청의 본문으로 사용할 객체를 지정해줄 수 있습니다!

 override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
               val resp:AuthResponse = response.body()!!
 				when(resp.code)
               {
                   1000 -> finish()
                   2016, 2018 -> {
                       binding.signUpEmailErrorTv.visibility = View.VISIBLE
                       binding.signUpEmailErrorTv.text = resp.message
                   }

               }
           }

when문을 통해서 실패 시 실패함수로 들어가는 것이 아닌 개발자가 의도한 코드로 들어가는 것을 확인할 수 있다.

0개의 댓글