반응형
day 13, day 14, day 15, day 16, day 17 빼먹음
레트로핏 예제
package com.example.retrofit_test_3
import com.google.gson.JsonElement
import retrofit2.Call
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
interface IRetro {
@FormUrlEncoded
@POST("/login")
fun loginRequest(
@Field("username")username:String,
@Field("password")password:String
): Call<JsonElement>
}
@Field
@Body
URL을 동적으로 지정 @Path :
쿼리를 지정@Query, @QueryMap :
HEADER 지정하기 @Header
메소드 : @GET, @POST, @PUT, @DELETE, @HEAD
DTO를 사용할 때 : @SerializedName("request"), @SerializedName("response")
등등이 있습니다.
JsonElement를 받도록 인터페이스를 작성해줍니다.
package com.example.retrofit_test_3
enum class LoginResponse {
OK,
FAIL
}
package com.example.temp_retrofit
import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
//싱글톤 패턴의 적용되어 객체가 한 번만 생성됨
object RetrofitClient {
private var retrofit:Retrofit? = null
private val TAG:String = "로그"
fun getClient(baseUrl:String) :Retrofit?{
val okclientBuilder = OkHttpClient.Builder()
val loggingInterceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger{
override fun log(message:String){
Log.d(TAG, "Retrofit Client - log: $message")
}
})
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
okclientBuilder.addInterceptor(loggingInterceptor)
okclientBuilder.connectTimeout(10, TimeUnit.SECONDS)
//커넥션은 만들어졌지만 작업이 길어질때
okclientBuilder.readTimeout(10, TimeUnit.SECONDS)
//커넥션은 만들어졌지만 클라이언트가 데이터를 보내는 시간이 길어질때
okclientBuilder.writeTimeout(10, TimeUnit.SECONDS)
okclientBuilder.retryOnConnectionFailure(true)
if(retrofit == null){
retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(okclientBuilder.build())
.build();
}
return retrofit
}
}
object로 클래스를 정의하면, 싱클턴(Singleton) 패턴이 적용되어 객체가 한번만 생성되도록 합니다.
object는 익명객체를 생성할 때도 사용됩니다.
package com.example.retrofit_test_3
import com.google.gson.JsonElement
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class RetrofitManager {
private val BASE_URL = "http://192.168.21.126:5000";
private val TAG = "로그"
companion object{
val instance = RetrofitManager()
}
private val iRetrofit:IRetro?
= RetrofitClient.getClient(BASE_URL)?.create(IRetro::class.java)
fun login(username:String, password:String, completion:(LoginResponse, String)->Unit){
val call = iRetrofit?.loginRequest(username, password)?:return
call.enqueue(object: Callback<JsonElement> {
override fun onFailure(call:Call<JsonElement>, t:Throwable){
completion(LoginResponse.FAIL, t.toString())
}
override fun onResponse(call: Call<JsonElement>, response: Response<JsonElement>){
if(response.code()!=200){
completion(LoginResponse.FAIL, response.body().toString())
}else{
completion(LoginResponse.OK, response.body().toString())
}
}
})
}
}
package com.example.retrofit_test_3
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AlertDialog
import com.example.retrofit_test_3.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
val TAG = "태그"
lateinit var binding:ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.loginButton.setOnClickListener {
Log.d(TAG, "loginbutton click" )
val username = binding.usernameInput.text.toString()
val password = binding.passwordInput.text.toString()
loginRequest(username, password)
}
}
fun loginRequest(username:String, password:String){
val dialogBuilder = AlertDialog.Builder(this@MainActivity)
if(username.isEmpty() || password.isEmpty()){
dialogBuilder.setTitle("알림")
dialogBuilder.setMessage("빈칸을 전부 채워주세요")
dialogBuilder.setPositiveButton("확인",null)
dialogBuilder.show()
}else{
RetrofitManager.instance.login(username=username, password=password, completion = {
loginResponse, response ->
when(loginResponse){
LoginResponse.FAIL->{
dialogBuilder.setTitle("알림")
dialogBuilder.setMessage("로그인 실패")
dialogBuilder.setPositiveButton("확인", null)
dialogBuilder.show()
}
LoginResponse.OK -> {
dialogBuilder.setTitle("알림")
dialogBuilder.setMessage("로그인성공")
dialogBuilder.setPositiveButton("확인",null)
dialogBuilder.show()
}
}
})
}
}
}
this@MainActivity) 는 qualified this 입니다.