티스토리 뷰

1. Android Retrofit (X-Auth-Token 과 함께 Post 하기) (코틀린)

REST API 를 사용해서 문제를 해결해야할 경우 X-Auth-Token(토큰) 이 주어졌고 이를 사용해서 관리 키를 POST 메소드로 받아오려고 할때 필요한 코드를 기록해보려고합니다. (삽질 방지용 글)

Field, FieldMap, Query 등을 사용해서 요청할 경우 되지 않아서 좀 삽질을 했습니다만 결론적으로는 Body 를 사용해서 얻어와야 했습니다. (정확히 말하면 @Body 어노테이션)

1.1. POST Example

curl -X POST {BASE_URL}/start \
     -H 'X-Auth-Token: {X_AUTH_TOKEN}' \
     -H 'Content-Type: application/json' \
     -d '{
         "problem": 1
     }'

POST 메소드로 보낼 형식 예시는 위와 같았습니다.

1.2. Data Class (DTO)

data class StartDto(
    val auth_key: String,
    val problem: Int,
    val time: Int
)

요청으로 받아올 데이터 클래스는 위와 같고 이는 인증키, 문제번호, 시간 등으로 이루어져 있었습니다.

1.3. Service Interface

import com.lilcode.test.kakao2021challenges.dto.StartDto
import retrofit2.Call
import retrofit2.http.*

interface GameService {
    @Headers(
        "X-Auth-Token: xxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
        "Content-Type: application/json")
    @POST("start")
    fun start(@Body params: HashMap<String, Int>): Call<StartDto>
}

예시에서 요구하는 것과 마찬가지로 x auth token, content-type 을 헤더에 정의해주었고 POST 메소드로 start 주소에 Body에 파라미터 하나를 포함해서 요청하려고 위와 같이 정의해주었습니다.

2. Use Retrofit

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.lilcode.test.kakao2021challenges.databinding.ActivityMainBinding
import com.lilcode.test.kakao2021challenges.dto.StartDto
import com.lilcode.test.kakao2021challenges.service.GameService
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class MainActivity : AppCompatActivity() {
    private var _binding: ActivityMainBinding? = null
    private val binding get() = requireNotNull(_binding)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val retrofit = Retrofit.Builder()
            .baseUrl("https://xxx.xxx.xxx.amazonaws.com/prod/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        val params = HashMap<String, Int>()
        params["problem"] = 1

        retrofit.create(GameService::class.java).also{
            it.start(params)
                .enqueue(object: Callback<StartDto>{
                    override fun onResponse(call: Call<StartDto>, response: Response<StartDto>) {
                        if (response.isSuccessful.not()) {
                            Log.e("@LSS", "response fail")
                            Log.e("@LSS", response.message())
                            
                            return
                        }

                        response.body()?.let { startDto ->
                            Log.d("@LSS", "auth_key: ${startDto.auth_key}, problem: ${startDto.problem}, time: ${startDto.time}")
                        }
                    }

                    override fun onFailure(call: Call<StartDto>, t: Throwable) {
                        Log.e("@LSS", "connect fail")
                    }
                })
        }
    }
}

Retrofit 빌더로 레트로핏 객체를 하나 생성하고 아까 정의한 서비스 인터페이스를 사용해서 서비스를 생성해서 연결해줍니다. 이후 enqueue 를 통해 응답 시 처리를 구현해주었습니다.

반응형

2.1. 결과

D/@LSS: auth_key: xxxx-xxxx-xxxx-xxxx-xxxxxxxxxx, problem: 1, time: 0

결과적으로 디버깅 메세지를 통해서 인증키를 정상적으로 받아온 것을 확인할 수 있습니다. (본문에 주소와 키는 xxx 를 사용해서 실제 주소와 키를 노출하지 않았습니다.)

Retrofit Version

사용한 레트로핏 버전은 아래와 같습니다.

    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

2021.09.18 - [유용한 정보/IT·컴퓨터] - 갤럭시 워치4 롤렉스 페이스 적용기 (galaxy watch 4 classic Rolex face)

2021.09.12 - [Android/Kotlin] - [Kotlin] 코틀린 인터페이스의 Default implementation 과 JAVA

2021.08.18 - [Android/App] - [Android] K-MOOC 강좌정보 서비스 앱 (2021 app dev-matching)

댓글
최근에 올라온 글
최근에 달린 댓글
네이버 이웃추가
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함