[안드로이드 Retrofit2] 시작하기
조건 및 설정
ㆍJava 7, Android 2.3 이상
ㆍ종속성 설정
1 | implementation 'com.squareup.retrofit2:retrofit:2.5.0' | cs |
간단한 Retrofit 생성 예제
ㆍ어노테이션은 요청을 처리하는 방법을 나타냅니다.
1 2 3 4 | public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); } | cs |
ㆍGitHubService 인터페이스를 구현하여 Retrofit 객체를 생성합니다.
1 2 3 4 5 | Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .build(); GitHubService service = retrofit.create(GitHubService.class); | cs |
ㆍGitHubService를 통해 생성된 Call은 동기 또는 비동기 HTTP 요청을 만들 수 있습니다.
1 | Call<List<Repo>> repos = service.listRepos("octocat"); | cs |
method 요청하기
ㆍ요청할 method와 URL을 포함하는 어노테이션을 추가해야 합니다.
ㆍ어노테이션 종류: @GET, @POST, @PUT, @DELETE, @HEAD
1 | @GET("users/list") | cs |
ㆍURL에 쿼리도 지정할 수 있습니다.
1 | @GET("users/list?sort=desc") | cs |
URL 지정
ㆍ@Path를 사용하여 URL을 동적으로 지정할 수 있습니다.
1 2 | @GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId); | cs |
ㆍ@Query를 사용하여 쿼리를 지정할 수 있습니다.
1 2 | @GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort); | cs |
ㆍ@QueryMap을 사용하여 많은 쿼리를 한 번에 지정할 수 있습니다.
1 2 | @GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options); | cs |
BODY 요청하기
ㆍ@Body를 사용하여 HTTP의 body로 사용할 객체를 지정할 수 있습니다.
1 2 | @POST("users/new") Call<User> createUser(@Body User user); | cs |
ㆍ객체는 추가된 converter를 사용하여 변환할 수 있습니다.
ㆍconverter를 추가하지 않으면 RequestBody만 사용할 수 있습니다.
FORM ENCODED와 MULTIPART
ㆍ@FormUrlEncoded를 사용하여 form-encoded 데이터로 전송할 수 있습니다.
ㆍ@Field를 사용하여 key값은 어노테이션에, value값은 매개 변수에서 지정하면 됩니다.
1 2 3 | @FormUrlEncoded @POST("user/edit") Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last); | cs |
ㆍ@Multipart를 사용하여 Multipart 요청을 할 수 있습니다.
ㆍ@Part를 사용하여 각 Part를 지정할 수 있습니다.
1 2 3 | @Multipart @PUT("user/photo") Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description); | cs |
ㆍconverter와 RequestBody를 사용할 수 있습니다.
HEADER 지정하기
ㆍ@Headers를 사용하여 헤더를 지정할 수 있습니다.
1 2 3 | @Headers("Cache-Control: max-age=640000") @GET("widget/list") Call<List<Widget>> widgetList(); | cs |
1 2 3 4 5 6 | @Headers({ "Accept: application/vnd.github.v3.full+json", "User-Agent: Retrofit-Sample-App" }) @GET("users/{username}") Call<User> getUser(@Path("username") String username); | cs |
ㆍ@Header를 사용하여 헤더를 동적으로 업데이트할 수 있습니다.
ㆍ매개 변수 값이 null이면 헤더가 추가되지 않습니다.
1 2 | @GET("user") Call<User> getUser(@Header("Authorization") String authorization) | cs |
ㆍ쿼리와 마찬가지로 @HeaderMap을 사용할 수 있습니다.
1 2 | @GET("user") Call<User> getUser(@HeaderMap Map<String, String> headers) | cs |
ㆍ모든 요청마다 헤더를 추가해야 한다면 OkHttp interceptor를 사용하면 됩니다.
동기 VS 비동기
ㆍCall 인스턴스는 동기 또는 비동기로 요청할 수 있습니다.
ㆍ각 인스턴스들은 동기와 비동기 중 한가지 방식만 사용할 수 있지만, clone() 메소드를 통해 새 인스턴스를 생성하면 다른 방식도 사용할 수 있습니다.
ㆍ안드로이드에서 callback은 메인 스레드에서 실행됩니다.
Retrofit 설정
ㆍRetrofit은 API 인터페이스를 call 가능한 객체로 바꿔주는 클래스입니다.
ㆍCONVERTERS
- Gson: com.squareup.retrofit2:converter-gson
- Jackson: com.squareup.retrofit2:converter-jackson
- Moshi: com.squareup.retrofit2:converter-moshi
- Protobuf: com.squareup.retrofit2:converter-protobuf
- Wire: com.squareup.retrofit2:converter-wire
- Simple XML: com.squareup.retrofit2:converter-simplexml
- Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars
ㆍGsonConverterFactory 클래스를 사용하여 Gson converter를 추가하는 예제입니다.
1 2 3 4 5 6 | Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://api.github.com") .addConverterFactory(GsonConverterFactory.create()) .build(); GitHubService service = retrofit.create(GitHubService.class); | cs |
출처
https://square.github.io/retrofit/