총 6단계로 이루어지고 예제로 적용해보며 설명하겠습니다.
// build.gradle
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"
<uses-permission android:name="android.permission.INTERNET" />
// NetworkModule.kt
package com.example.retrofitpractice
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
const val BASE_URL = "https://edu-api-test.softsquared.com"
fun getRetrofit(): Retrofit {
val retrofit = Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create()).build()
return retrofit
}
// AuthResponse.kt
package com.example.retrofitpractice
import com.google.gson.annotations.SerializedName
data class AuthResponse (
@SerializedName(value = "isSuccess") val isSuccess: Boolean,
@SerializedName(value = "code") val code: Int,
@SerializedName(value = "message") val message: String
)
// api 명세서
{
"isSuccess": true,
"code": 1000,
"message": "Successful!"
}
// User.kt
package com.example.retrofitpractice
import com.google.gson.annotations.SerializedName
data class User (
@SerializedName(value = "email") var email: String,
@SerializedName(value = "password")var password: String,
@SerializedName(value = "name")var name: String
)
// api 명세서
{
"email": "qwerty@gmail.con",
"password": "qwertyaaa",
"name": "쿼티"
}
// AuthRetrofitInterface.kt
package com.example.retrofitpractice
import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.POST
interface AuthRetrofitInterFace {
@POST("/users") // @Method(api address)
fun signUp(@Body user:User): Call<AuthResponse>
}
// api 명세서
Method: POST
API Address: /users
// SignUpView.kt
package com.example.retrofitpractice
interface SignUpView {
fun onSignUpSuccess()
fun onSignUpFailure()
}
// AuthService.kt
package com.example.retrofitpractice
import android.util.Log
import android.view.View
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class AuthService {
// 1단계
private lateinit var signUpView: SignUpView
fun setSignUpView(signUpView: SignUpView) {
this.signUpView = signUpView
}
// 2단계
fun signUp(user: User) {
val authService = getRetrofit().create(AuthRetrofitInterFace::class.java)
authService.signUp(user).enqueue(object: Callback<AuthResponse> {
override fun onResponse(call: Call<AuthResponse>, response: Response<AuthResponse>) {
Log.d("SIGNUP/SUCCESS", response.toString())
val resp: AuthResponse = response.body()!!
when(resp.code) {
1000 -> signUpView.onSignUpSuccess()
else -> signUpView.onSignUpFailure()
}
}
override fun onFailure(call: Call<AuthResponse>, t: Throwable) {
Log.d("SIGNUP/FAILURE", t.message.toString())
}
})
}
}
// MainActivity.kt
package com.example.retrofitpractice
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Toast
import com.example.retrofitpractice.databinding.ActivityMainBinding
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
// 1단계
class MainActivity : AppCompatActivity(), SignUpView {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.joinSubmitBtn.setOnClickListener {
signUp()
}
}
private fun getUser(): User {
val email: String = binding.joinEmailEt.text.toString()
val password: String = binding.joinPasswordEt.text.toString()
val name: String = binding.joinNameEt.text.toString()
return User(email, password, name)
}
private fun signUp() {
if(binding.joinEmailEt.text.toString().isEmpty()) {
Toast.makeText(this, "이메일 형식이 잘못되었습니다.", Toast.LENGTH_SHORT).show()
return
}
if(binding.joinNameEt.text.toString().isEmpty()) {
Toast.makeText(this, "이름 형식이 잘못되었습니다.", Toast.LENGTH_SHORT).show()
return
}
if(binding.joinPasswordEt.text.toString() != binding.joinPasswordCheckEt.text.toString()) {
Toast.makeText(this, "비밀번호가 일치하지 않습니다.", Toast.LENGTH_SHORT).show()
return
}
// 2단계
val authService = AuthService()
authService.setSignUpView(this)
authService.signUp(getUser())
}
// 1단계: 상속받은거 정의
override fun onSignUpSuccess() {
Toast.makeText(this, "회원가입에 성공했습니다", Toast.LENGTH_SHORT).show()
}
override fun onSignUpFailure() {
TODO("Not yet implemented")
}
}