#1 ์ด์ ๊ธ
[Android] Retrofit - ๊ธฐ์ด
#1 ์ด์ ๊ธ [Android] Retrofit - ๋ฐฐ๊ฒฝ๊ณผ ๊ตฌ์กฐ#1 Restrofit์ ๋ฐฐ๊ฒฝ#1-1 REST API REST API (REpresentational State Transfer Application Programming Interface)#1 ๋ฌด์(What)์ ๋ํ API์ธ๊ฐ?#1-1 ๊ฐ์REST(REpresentational State Transfer) ๋๋
kenel.tistory.com
์ ๊ฒ์๊ธ์ ์์ฑ๋ ์ฑ์ ์ผ๋ถ ์์ ํด์, ์๋ฒ์ Post ์์ฒญ์ ํด๋ณธ๋ค. (์ฐธ์กฐ: REST API)
#2 ์ฝ๋ ์์
#2-1 AlbumService.kt
// package com.example.post
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
interface AlbumService {
...
@POST("/albums")
suspend fun uploadAlbum(@Body album: AlbumsItem): Response<AlbumsItem>
}
Post ์์ฒญ ๋ํ ๋ฐํํ์ด ์กด์ฌํ๋ค. ์๋ฒ๋ก ๋ณด๋ธ Post ์์ฒญ์ด ์ด๋ป๊ฒ ์ฒ๋ฆฌ๋๋๊ฐ์ ๋ํ ์๋ต(Response)๊ฐ ํ์ํ๊ธฐ ๋๋ฌธ์ด๋ค.
#2-2 MainActivity.kt
...
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
...
val responseLiveData: LiveData<Response<AlbumsItem>> = liveData {
val album = AlbumsItem(7, 12, "Post practice") // AlbumsItem ๊ฐ์ฒด๋ฅผ ํ๋ ์ฝ๋ฉ
val response = retrofitService.uploadAlbum(album)
emit(response)
}
responseLiveData.observe(this, Observer {
displayListOnScreen(textView, it)
})
}
private fun displayListOnScreen(textView: TextView, response: Response<AlbumsItem>) {
val item = response.body()
if (item != null) {
val result =
"User id : ${item.userId}" + "\n" +
"Album id : ${item.id}" + "\n" +
"Album Title : ${item.title}" + "\n\n\n"
textView.append(result)
}
}
}
LiveData Builder๋ก ๋ง๋ responseLiveData๋ฅผ ์์ ํ๋ค. responseLiveData.observe ์์ ์๋ displayListOnScreen()๋ ์๋ง๊ฒ ์์ ํ๋ค.
#3 ์๋ ํ์ธ
#2-2์์ ๋ง๋ Album ๊ฐ์ฒด์ Album id๋ 12์ด์๋ค. ๊ทธ๋ฐ๋ฐ ์ด์งธ์ ์๋ฒ์ Post๋ id๋ 101์ธ๊ฐ? ์ด๋ ์๋ฒ๊ฐ ํด๋ผ์ด์ธํธ๊ฐ ์ ์ํ id๋ฅผ ๋ฌด์ํ๊ณ ์์์ id๋ฅผ ํ ๋นํ๊ธฐ ๋๋ฌธ์ด๋ค. ๋ฐ์ดํฐ๋ฒ ์ด์ค์์ id๋ ๊ฑฐ์ ๋ชจ๋ ์๋ ์ฆ๊ฐ(Auto Increment)๋๋ค. ๊ทธ๋์ผ ๊ธฐ๋ณธ ํค๋ก์์ ์ญํ ์ ์ํํ๊ธฐ ์ํ ๋ฌด๊ฒฐ์ฑ์ ๊ฐ์ถ ์ ์๋ค. ๋ฐ๋ฉด, User id๋ ๊ธฐ๋ณธํค๋ ์๋๊ณ ์ค๋ณต์ ํ์ฉํ๋ Column์ด๊ธฐ์ #2-2์์ ์ ์ํ ๊ฐ์ด ๊ทธ๋๋ก ์ ๋ฌ๋์๋ค.
#4 ์์ฑ๋ ์ฑ
android-practice/retrofit/Post at master · Kanmanemone/android-practice
Contribute to Kanmanemone/android-practice development by creating an account on GitHub.
github.com
'๊นจ์ ๊ฐ๋ ๐ > Android' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Android] Notifications - PendingIntent (0) | 2024.06.12 |
---|---|
[Android] Notifications - ๊ธฐ์ด (0) | 2024.06.12 |
[Android] Retrofit - Logging, Timeout ๊ด๋ฆฌ (Interceptor) (0) | 2024.06.11 |
[Android] Retrofit - MVVM ๊ตฌ์กฐ (0) | 2024.06.05 |
[Android] Retrofit - ๊ธฐ์ด (0) | 2024.05.29 |