Retrofit์ REST API์ ์ฝ๊ฒ ํต์ ํ ์ ์๋๋ก ๋์์ฃผ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ ๋๋ค.
โ JSON์ ์๋์ผ๋ก ์ง๋ ฌํ/์ญ์ง๋ ฌํํ๋ฉฐ, ๋น๋๊ธฐ ๋คํธ์ํฌ ์์ฒญ์ ๊ฐํธํ๊ฒ ์ฒ๋ฆฌํ ์ ์์ต๋๋ค.
build.gradle)Retrofit์ ์ฌ์ฉํ๋ ค๋ฉด Gradle์ ์์กด์ฑ ์ถ๊ฐ๊ฐ ํ์ํฉ๋๋ค.
build.gradle (๋ชจ๋ ์์ค)groovy
๋ณต์ฌํธ์ง
dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0' // JSON ๋ณํ๊ธฐ
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.3' // ๋๋ฒ๊น
์ฉ
}
โ ์ค๋ช
retrofit:2.9.0 โ Retrofit ๊ธฐ๋ณธ ๋ผ์ด๋ธ๋ฌ๋ฆฌconverter-gson โ JSON ๋ฐ์ดํฐ๋ฅผ ์๋ ๋ณํlogging-interceptor โ ๋คํธ์ํฌ ์์ฒญ์ ๋ก๊ทธ๋ก ํ์ธ ๊ฐ๋ฅRetrofit์ ์ฌ์ฉํ๋ ค๋ฉด API ์์ฒญ์ ์ ์ํ๋ ์ธํฐํ์ด์ค๊ฐ ํ์ํฉ๋๋ค.
ApiService.javajava
๋ณต์ฌํธ์ง
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Path;
import java.util.List;
public interface ApiService {
@GET("posts")
Call<List<Post>> getPosts(); // ๋ชจ๋ ๊ฒ์๋ฌผ ๊ฐ์ ธ์ค๊ธฐ
@GET("posts/{id}")
Call<Post> getPostById(@Path("id") int id); // ํน์ ๊ฒ์๋ฌผ ๊ฐ์ ธ์ค๊ธฐ
}
โ ์ค๋ช
@GET("posts") โ https://jsonplaceholder.typicode.com/posts ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์ด@GET("posts/{id}") โ ๋์ ํ๋ผ๋ฏธํฐ(id)๋ฅผ URL์ ์ถ๊ฐ