Android Retrofit2 관련 설정 총 정리 (HTTP 통신, Gson paring)
Android Retrofit2 관련 설정 총 정리 (HTTP 통신, Gson paring) — #개발자의도구들 #retrofit2 #안드로이드인터넷 #안드로이드HTTP #안드로이드RETROFIT2 🚨?...
#Vue js#Naver Blog
#개발자의도구들 #retrofit2 #안드로이드인터넷 #안드로이드HTTP #안드로이드RETROFIT2
🚨📝 📖 📒✏️💡🔍
AI스쿨 msa기반 java 백엔드 코스 중에 공부한 내용을 작성하였습니다
\* 현재 Spring x 프로젝트를 진행하고 있습니다. 전체 목차를 보시려면 여기를 눌러주세요.
\* 해당 프로젝트 이전에 공부한 내용을 보시려면 여기를 눌러주세요.
Retrofit2 관련 설정 총 정리
바로 이전 글에는 Retrofit2를 사용하여 HTTP 통신시 클래스 구조를 어떻게 나누면 좋을지에 대한 부분이었다면, 이번에는 Retrofit2가 제대로 동작하게끔 하기 위해 필요한 설정들을 정리하였습니다.
Index
- Purpose
- DB Design
- Code
- Entity
- Controller
- Service
- Repostiory
- Question
- Answer
- Feedback
| 💡 Tips |
|---|
Purpose
Retrofit2 사용시 필요한 모든 설정을 정리하여, 프로젝트 진행이 매끄럽게 되도록 하기 위함
네트워크 설정
HTTP 전송 오류
CLEARTEXT communication to localhost not permitted by network security policy
오류 원인: 안드로이드 API 버전에 따른 HTTP 통신 지원 X : HTTPS로만 (Android9: API LEVEL 28부터)
해결 방안:
1. network_security_config.xml 파일 생성 : res/xml 경로
아래 코드를 넣는다.
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">10.0.2.2</domain>
</domain-config>
</network-security-config>
💡 Android에서는 Localhost로 요청을 전송하는 것이 아닌 10.0.2.2:port로
로컬 서버에 요청을 보낼 수 있습니다.
AndroidManifest.xml 파일
<uses-permission android:name="android.permission.INTERNET" />
<application?
android:networkSecurityConfig="@xml/network_security_config"
</application>
위에서 생성한 파일을 AndroidManifest.xml에 등록해주고, user-permission에서 INTERNET을 허용합니다.
PARSING 설정
Expected BEGIN_OBJECT but was STRING at line 1 column
96path: $.boradResults[0].createdAt
현재 포스팅 데이터를 BoardResult로 받고 있는데, Gson에서 parsing할 수 없어서 발생하는 오류
package com.example.myapplication.dto
import java.time.LocalDateTime
data class BoardResult(
val id: Long,
val writerName: String,
val textContent: String,
val fileApiUrl: String?,
val createdAt: LocalDateTime,
val lastModifiedAt: LocalDateTime, // Gson에서 parsing이 안됨
val readingCount: Long,
val commentCount:Int,
val jsonComment: String?,
val likeCount: Int
)
이때는 Gson에 관련 설정을 추가해주고, DI로 넣어줍니다.
class LocalDateTimeAdapter : JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
private val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME
override fun serialize(src: LocalDateTime?, typeOfSrc: Type?, context: JsonSerializationContext?): JsonElement {
return JsonPrimitive(formatter.format(src))
}
@Throws(JsonParseException::class)
override fun deserialize(json: JsonElement, typeOfT: Type, context: JsonDeserializationContext): LocalDateTime {
return LocalDateTime.parse(json.asString, formatter)
}
}
LocalDateTimeAdpater를 설정해주고, Gson에 등록, 등록된 Gson은 Retrofit에 등록합니다.
package com.example.myapplication.di
import com.example.myapplication.utils.LocalDateTimeAdapter
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.time.LocalDateTime
import java.util.concurrent.TimeUnit
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object RetrofitModule {
@Singleton
@Provides
fun provideGson(): Gson {
return GsonBuilder()
.registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter())
.create()
}
// Gson에 LocalDateTimeAdpater를 등록
@Singleton
@Provides
fun provideRetrofit(gson: Gson): Retrofit {
val httpLoggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val okHttpClient = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.readTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.build()
return Retrofit.Builder()
.baseUrl("http://10.0.2.2:8080")
.addConverterFactory(GsonConverterFactory.create(gson)) // Retrofit에 Gson등록
.client(okHttpClient)
.build()
}
}