Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- Generic
- Kotlin
- ReactNative
- class component
- Swift
- Interface
- list
- vuex
- ConstraintLayout
- mongoose
- map
- Service
- lifecycle
- enum
- 생명주기
- docker-compose
- react native
- elementAt
- recyclerview
- LiveData
- MINUS
- Filter
- animation
- AWS
- Foreign Key
- function
- docker
- union
- collection
- CLASS
Archives
- Today
- Total
개발 일기
Retrofit 이란? 본문
Retrofit 이란?
네트워크로 부터 전달된 데이터를 필요한 객체의 형태로 변환을 해주는 HttpClient 라이브러리입니다.
사용법 :)
Gradle
implementation "com.squareup.retrofit2:retrofit:$project.retrofitVersion"
// 원하는 형태로 전달 받기 위해서 필요
implementation "com.squareup.retrofit2:converter-gson:$project.retrofitVersion"
먼저 Api 보내는 부분을 interface로 정의를 합니다.
interface MasterApi {
@GET(CodeUtils.Network.Api.SEARCH_EMAIL)
@JsonAndGraphConverters.Json
suspend fun searchEmail(@Query(CodeUtils.Network.Params.EMAIL) email : String) : ResponseBody
}
기본적으로 Retrofit은 GET , POST , PUT , DELETE을 요청합니다.
GET - 데이터를 가져올 때 사용
POST - 데이터를 INSERT 사용
PUT - 데이터를 수정할 때 사용
DELETE - 데이터를 삭제할 때 사용
다음으로 Retrofit 선언부 입니다.
fun provideOkHttpClient(context :Context) : OkHttpClient {
val interceptor = HttpLoggingInterceptor()
// 개발용으로 Retrofit Log를 넣을수 있습니다.
interceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.NONE else HttpLoggingInterceptor.Level.BODY // logging
// interface로 Header를 넣을수도 있고, 공통적으로 이런 방법으로도 넣을수 있습니다.
val headerInterceptor = Interceptor {
val newRequeset = it.request().newBuilder().addHeader(
CodeUtils.PreferenceCode.TOKEN, PreferenceHelper.getPref( context, CodeUtils.PreferenceCode.TOKEN, "") ?: ""
).build()
it.proceed(newRequeset)
}
return OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS) // Tcp HandShake가 완료되기까지 지속되는 시간
.writeTimeout(10, TimeUnit.SECONDS) // 서버에 바이트 보내는 시간
.readTimeout(10, TimeUnit.SECONDS) // 서버 응답 시간
.addInterceptor(interceptor)
.addInterceptor(headerInterceptor)
.build()
}
fun provideRetrofit(context : Context , @NonNull okHttpClient : OkHttpClient) : Retrofit{
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl(CodeUtils.Network.MASTER_BASE_URL)
.addConverterFactory(GsonConverterFactory.create()) //JSON을 원하는 객채로 변환을 시켜줍니다.
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // Call 객체 대신에 rxjava 형식으로 변환을 시킬수 있습니다.
.build()
}
fun getApiCallInterface(retrofit : Retrofit) : MasterApi {
return retrofit.create(MasterApi::class.java)
}
'Client > 안드로이드' 카테고리의 다른 글
ImageView , AppCompatImageView 차이 ? (0) | 2020.03.14 |
---|---|
ImageView 란? (0) | 2020.03.14 |
Git push가 제대로 작동하지 않을 경우 !? (0) | 2020.03.12 |
View ? (0) | 2020.03.11 |
Edit Text ? (0) | 2020.03.10 |
Comments