[ Retrofit2. 2.사용방법  (Retrofit 2로 HTTP 호출하기) ]

 

1. 정의

    - Retrofit은 안드로이드와 Java 애플리케이션을 위한 라이브러리로, 안전한 타입(type-safe) 방식의 HTTP 클라이언트 이다. 이번 글에서는 Retrofit 2 HTTP 클라이언트의 사용 복잡성과 앱 적용 시의 유용성을 살펴볼 예정이다.

 

 

1. 네트워크 사용을 위해서 AndroidManifest.xml 에서 Internet Permission 을 허용해야 됨

 

 <manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

 

 

2. Retrofit을 사용하기 위해서 build.gradle 파일에 라이브러리 추가

   - Retrofit2만 적용시

 

 dependencies {
    compile 'com.squareup.retrofit2:retrofit:2.1.0'

}

 

  - Retrofit2 + gson 적용시

 

 dependencies {
    compile 'com.google.code.gson:gson:2.7'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.retrofit2:converter-gson:2.1.0' 
}

 

 

 

3. 모델 클래스 만들기(데이터 그릇)

 

 public class Contributor {
 
  String login;
  String html_url;
 
  int contributions;
 
  @Override
  public String toString() {
    return login + "(" + contributions + ")";
  }
}

 

4. HTTP 통신을 하기 위한 서비스 인터페이스를 생성

 

 public interface GitHubService {
 
  @GET("repos/{owner}/{repo}/contributors")
  Call<List<Contributor>> repoContributors(
      @Path("owner") String owner
      , @Path("repo") String repo);
}

 

5. Retrofit 객체를 GitHubService 에 생성

   기본적인 Retrofit 객체 생성 형태는 아래와 같지만,

 

 public static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("https://api.github.com/")
            .build();

.addConverterFactory(GsonConverterFactory.create());

는 받아오는 Json 형식의 데이터를 Java 객체 형태로 변환 또는 반대 형식으로 변환시켜주는 Gson 라이브러리를 사용해야하기 때문에 수정해야 됨.

 

 

 public interface GitHubService {
 
  @GET("repos/{owner}/{repo}/contributors")
  Call<List<Contributor>> repoContributors(
      @Path("owner") String owner
      , @Path("repo") String repo);
 
  public static final Retrofit retrofit = new Retrofit.Builder()
      .baseUrl("https://api.github.com/")
      .addConverterFactory(GsonConverterFactory.create())
      .build(); 
}

 

6. HTTP 호출

   동기적으로 HTTP 를 호출하기 위해서 인터페이스를 구현하고

   Call 호출하기 위한 형태는 아래와 같다.

 

 GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
 Call<List<Contributor>> call = gitHubService.repoContributors(“square”, “retrofit”);
 List<Contributor> result = call.execute().body();

 

 그러나 Android 에서는 MainThread(UI Thread) 에서 네트워크 통신을 할 수 없도록 되어 있다.
위의 형태로 돌릴 경우 아래와 같은 에러 메세지가 떨어지게 된다.

 

 02-04 19:32:55.190 1678-1678/com.example.jihoonryu.retrofit2_test E/AndroidRuntime:
 FATAL EXCEPTION: main
 Process: com.example.jihoonryu.retrofit2_test, PID: 1678
 android.os.NetworkOnMainThreadException

 

그렇기 때문에 AsyncTask 를 통해서 백그라운드 스레드에서 작동을 시켜야 한다.

 

- 동기(Synchronous)

 

new AsyncTask<Void, Void, String>() {
 
    @Override
    protected String doInBackground(Void... params) {
      GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
      Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
     
    try {
        return call.execute().body().toString();
      } catch (IOException e) {
        e.printStackTrace();
      }
 
      return null;
    }
 
    @Override
    protected void onPostExecute(String s) {
      super.onPostExecute(s);
      TextView textView = (TextView) findViewById(R.id.textView);
      textView.setText(s);
    }
}.execute();

 

 Retrofit2 의 장점은 동기적이던 비동기적이던 구현하기 쉬움에 있다.
비동기적(Asynchronously) 으로 구현할 경우는 자체적으로 백그라운드 스레드를 타기 때문에 그냥 구현해주면 된다.

 

 -비동기(Asynchronous)

 

 

 GitHubService gitHubService = GitHubService.retrofit.create(GitHubService.class);
    Call<List<Contributor>> call = gitHubService.repoContributors("square", "retrofit");
    call.enqueue(new Callback<List<Contributor>>() {
      @Override
      public void onResponse(Call<List<Contributor>> call,
          Response<List<Contributor>> response) {
 
        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(response.body().toString());
      }
 
      @Override
      public void onFailure(Call<List<Contributor>> call, Throwable t) {
 
      }
});

 

 

 

 

참고] http://devuryu.tistory.com/44


1. Realm / Retorift2로 HTTP 호출하기
2. Retrofit 한글 소개
3. Getting started with Retrofit 2
4. Retrofit 2.0: The biggest update yet on the best HTTP Client Library for Android

'[Android] - 개념 > Retrofit2' 카테고리의 다른 글

Retrofit2. 3. 참고 URL  (0) 2017.03.13
hanjul에 추가할 주석문장  (0) 2017.03.13
Retrofit2. 1.기본 개념  (0) 2017.03.12
Posted by 농부지기
,