1. Retrofit?
Retrofit은 애플리케이션 통신에 사용되는 코드를 간편하게 사용할 수 있도록 도와주는 라이브러리이다. Json형식의 데이터를 주고받는다. 같이 사용되는 converter-gson이 있는데 이는 응답결과가 Json형식일때 객체로 변환해주는 아이이다.
만약 객체로 변환되지 않는 형태라면..? 그만 상상하자
Square에서 만든 라이브러리이다.
Link -> https://devflow.github.io/retrofit-kr/
Retrofit - 한글 문서
A type-safe HTTP client for Android and Java
devflow.github.io
2. gradle추가
최신버전 -> https://github.com/square/retrofit
GitHub - square/retrofit: A type-safe HTTP client for Android and the JVM
A type-safe HTTP client for Android and the JVM. Contribute to square/retrofit development by creating an account on GitHub.
github.com
app수준의 build.gradle에 아래의 두줄을 추가한다.
dependencies {
...
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}
3. Manifest.xml 추가
통신에는 당연히 인터넷을 사용해야하므로 아래의 코드를 추가 인터넷 권한을 얻는 코드이다.
<manifest>
<uses-permission android:name="android.permission.INTERNET" />
<application>
...
</application>
</manifest>
4. 사용
4-1 데이터 클래스 생성
통신에 사용될 데이터모델을 Json형태로 생성 나는 따로 DataModel.kt파일을 생성해서 통신에 사용될 data class들을 만들어줬다.
data json( //Json은 Key value형태이다. key = s, n
var s : String? =null,
var n : Int? =null
)
4-2 Retrofit 객체 초기화 및 Interface 생성
이전에 했던 프로젝트의 코드를 가져오는건데 그때는 Springboot로 서버를 만들었다. 이 때 배포하지않고 팀원 개인 desktop에서 포트포워딩해서 사용했었는데 그때 주소는 http://ip주소:포트번호 였다.
interface APIS {
@GET("요청 url")//Get Interface
@Headers("accept: application/json",
"content-type: application/json")
fun get(
): Call<json>
@POST("요청 url")//Post Interface
@Headers("accept: application/json",
"content-type: application/json")
fun post(
@Body jsonparams: json
): Call<json>
companion object {// Retrofit 객체 초기화
private const val BASE_URL = "통신할 주소"
fun create(): APIS {
val gson : Gson = GsonBuilder().setLenient().create()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
.create(APIS::class.java)
}
}
}
GET Interface Post Interface
- 기본 헤더 추가 : @Headers - 기본 헤더 추가 : @Headers
- function명 : fun get() - function명 : fun post
- return받을 json data class : Call<json> - Post할 json data class : @Body jsonparams : json
- return받을 json data class : Call
Retrofit객체는 companion object를 이용해서 Singleton으로 구현을 한다. Singleton으로 구현하지않으면 액티비티에서 Retrofit객체를 만들어줄 때 마다 새로운 객체가 생성되므로 메모리낭비 방지.
4-3 enqueue() 를 사용해 통신
val api = APIS.create()
val data : json = json("String", 0)
api.post(data).enqueue(object : Callback<json>{
override fun onResponse(call: Call<json>, response: Response<json>) {
//성공했을 때
}
override fun onFailure(call: Call<json>, t: Throwable) {
//실패했을 때
}
})
응답으로 온 json을 파싱하고 싶다면 response.body().s 형식으로 파싱을 진행하면 된다.
get은 데이터만 가져오므로 body에 아무것도 없다. ( data부분을 비워주면 됨.)
--------------------------------------------------------추가----------------------------------------------------------------------
- data class를 arrayList로 받고 싶을 때
data json(
var s : String? =null,
var n : Int? =null
)
data arr(
var a : String?
var array : ArrayList<json>
)
파싱 response.body().array[0].s 식으로 파싱
- data class 형태 한개만 arrayList로 받고 싶을 때
api.userJoin(data).enqueue(object : Callback<ArrayList<json>>{
override fun onResponse(call: Call<ArrayList<json>>, response: Response<ArrayList<json>>) {
//성공했을 때
}
override fun onFailure(call: Call<ArrayList<json>>, t: Throwable) {
//실패했을 때
}
})
response.body()[0].s 형태로 파싱
- Header에 Token을 추가하고 싶을 때
내가 했던 프로젝트에서는 로그인을 한 이후의 모든 요청은 Header에 Token값을 추가했다. spring boot에서 Token값의 key, value는 authoriztion : String 으로 고정되어있음을 유의하자.
프로젝트 끝내고 okhttp가 있다는 사실을 알았단건 안비밀...
/////////////////////////////////////////// 헤더에 Token을 넣고 싶을 때
@GET("요청 url")
@Headers("accept: application/json",
"content-type: application/json"
)
fun get(
@Header("Authorization") authorization : String
):Call<json>
//////////////////////////////////////////////헤더와 바디는 아래처럼 추가 가능
@POST("요청url")
@Headers(
"accept: application/json",
"content-type: application/json"
)
fun postGraph(
@Header("Authorization") authorization : String,
@Body jsomparams: json
):Call<json>
- 요청 url이 변동할 때
내가 했던 프로젝트에서는 사용자 id가 요청 url로 추가 입력이 되었었다.
/////////////////////////////////////////////요청 url이 변동할때
@GET("요청 url/{url}")
@Headers("accept: application/json",
"content-type: application/json"
)
fun get(
@Header("Authorization") authorization : String,
@Path("url") url : String
):Call<json>
print 구문에서 ${}처럼 {} 변수를 감싸준 후 function 인자로 @Path를 입력받을 수 있다.
여러 상황들이 구현되어있는 프로젝트를 git에 올려놨다. 패키지 정리도 안되어이있고 디자인 패턴이나 생명주기를 잘 모를때 액티비티 oncreat에 때려박은 프로젝트라서 민망하지만 ㅎㅎㅎㅎ 필하신분들은 보시길
https://github.com/lyh5427/Smart_gwnu/tree/master/app/src/main/java/com/example/smart_gwnu/restful
GitHub - lyh5427/Smart_gwnu
Contribute to lyh5427/Smart_gwnu development by creating an account on GitHub.
github.com
retrofit에 관련된 패키지로 링크 걸어놨습니다.
- 중간에 잘못된 부분이 있다면 댓글로 남겨주세요. 수정하겠습니다
- 더 알고 계시는게 있다면 댓글남겨주세요. 저에게 큰 도움이 됩니다!
'kotlin(공부방)' 카테고리의 다른 글
RESTful API?? (0) | 2022.04.14 |
---|
댓글