woong's

Android http Retrofit 사용하기 본문

Develop/Android

Android http Retrofit 사용하기

dlsdnd345 2016. 2. 13. 23:33
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

Android http Retrofit 사용하기



​안녕하세요. android http volley 라이브러리를 사용 했는데 ,  최근에 retrofit 이 좋다는 이야기들이 많아서

바꾸어 보려고 포스트를 작성하고 있습니다 .


​무엇이 바뀌고 , 좋아졌는지를 먼저 알아보는것이 우선인것 같습니다 .


1. 어노테이션을 통한 가독성 증가

2. 속도 증가



위 그래프를 보면 속도면에서 굉장히 좋은 것을 볼 수 있습니다 .


출처 : http://instructure.github.io/blog/2013/12/09/volley-vs-retrofit/ 



1. 준비 과정


1
2
3
4
5
6
7
dependencies {
 
    compile fileTree(dir: 'libs', include: ['*.jar'])
 
    compile 'com.squareup.retrofit:retrofit:1.9.0'
 
}
cs

 


retrofit 라이브러리를 추가 합니다 .


2. 사용방법


1. VO 생성


   통신을 통하여 받아 파싱할 데이터 VO 를 생성 합니다. 

   필자는 git api 호출 테스트를 해보기 위해서 아래와 같이 작성 하였습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Contributor {
 
    String login;
    int contributions;
 
    public String getLogin() {
        return login;
    }
 
    public void setLogin(String login) {
        this.login = login;
    }
 
    public int getContributions() {
        return contributions;
    }
 
    public void setContributions(int contributions) {
        this.contributions = contributions;
    }
}
cs



2. Interface 생성


1
2
3
4
5
6
7
8
9
10
11
public interface GitHubService {
 
    public static final String API_URL = "https://api.github.com";
 
    @GET("/repos/{owner}/{repo}/contributors")
    void contributors(
            @Path("owner"String owner,
            @Path("repo"String repo,
            Callback<List<Contributor>> callback
    );
}
cs


위 코드가 Retrofit에서 중요한 코드 입니다 .

메서드 매칭을 통해서 데이터를 주고 받고 api 호출하게 됩니다.

어노테이션을 통해서 가독성도 좋아지고 코드도 깔금해 졌습니다.


@GET : 호출할 url 

@Path : url 을 통해 전달될 Value

Callbak : 비동기 처리를 통해 api 데이터를 받기위한 콜백 메서드



3. Retrofit 설정 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
        /**
         * Gson 컨버터 이용
         */
        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .registerTypeAdapter(Date.classnew DateTypeAdapter())
                .create();
 
        /**
         * 레트로핏 설정
         */
        RestAdapter restAdapter = new RestAdapter.Builder()
                //로그 레벨 설정
                .setLogLevel(RestAdapter.LogLevel.FULL)
                //BASE_URL 설정
                .setEndpoint(GitHubService.API_URL)
                //Gson Converter 설정
                .setConverter(new GsonConverter(gson))
                .build();
cs


Retrofit 설정을 보시면 굉장히 유연한것 같습니다 .


LogLevel : 로그를 자세히 , 간단하게 옵션을 통해서 볼수 있습니다.

Endpoint : base_url 설정

Converter : (기본 Gson )  Converter 는 json , xml 파싱에 따라 변경 할 수 있습니다.


위와 같이 설정을 통해서 필요한 옵션을 선택적으로 변경 할 수 있습니다.


4. CallBack 메서드 생성


마지막으로 설정을 통해 api 호출 콜백 메서드를 설명드리겠습니다 .


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        /**
         * 통신 콜백 메서드
         */
        restAdapter.create(GitHubService.class).contributors("square""retrofit"new Callback<List<Contributor>>() {
 
            @Override
            public void success(List<Contributor> contributors, Response response) {
 
                Log.i(TAG, contributors.get(0).getLogin() + " (" + contributors.get(0).getContributions() + ")");
            }
 
            @Override
            public void failure(RetrofitError error) {
 
                Log.e(TAG, error.toString());
            }
        });
cs


코드를 보면 굉장히 깔끔 합니다 .


파라미터를 통해 전달할 값이 들어가고 콜백메서드를 통해서 비동기 처리를 통하여 데이터를 받고 있습니다 .

파싱또한 기본 내장 Gson 을 통해서 VO 만 맞춰주면 자동으로 파싱작업을 해주어서 편리 한것 같습니다 .


Comments