JNU-econovation / Dotoring_AOS

더지팀 안드로이드 레포지토리
MIT License
0 stars 1 forks source link

회원가입 기능 전반적 구현 #47

Open Hyeonz1 opened 1 year ago

Hyeonz1 commented 1 year ago

[로그인에서 token을 넣기 위한 retrofit 구현 중 이슈 발생]

val otherClient: OkHttpClient = OkHttpClient.Builder() .addInterceptor(interceptor) .cookieJar(JavaNetCookieJar(CookieManager())) .build()

val gson : Gson = GsonBuilder() .setLenient() .create()

val retrofit: Retrofit = Retrofit.Builder() .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build()

- 변한 코드
```kotlin
val client: OkHttpClient = OkHttpClient.Builder()
    .addInterceptor(AppInterceptor())
    .cookieJar(JavaNetCookieJar(CookieManager()))
//    .addInterceptor(HttpLoggingInterceptor().apply {
//        level = HttpLoggingInterceptor.Level.BODY
//    })
    .build()

val gson : Gson = GsonBuilder()
    .setLenient()
    .create()

val retrofit: Retrofit = Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(GsonConverterFactory.create(gson))
    .client(client)
    .build()

class AppInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain) : Response = with(chain) {
        val accessToken = MyApplication.prefs.getString("Authorization", "") // ViewModel에서 지정한 key로 JWT 토큰을 가져온다.
        val refreshToken = MyApplication.prefs.getRefresh("Cookie", "")
        val newRequest = request().newBuilder()
            .addHeader("Authorization", accessToken) // 헤더에 authorization라는 key로 JWT 를 넣어준다.
            .addHeader("Cookie", refreshToken)
            .build()
        proceed(newRequest)
    }
}