1. Retrofit ?

 

 

모바일에서 HTTP API통신을 경우

많이 사용하는 라이브러리이다.

 

Retrofit은 Gson, Jackson 등 여러 컨버터를

지원하여 다양한 형태의 데이터를 

편하게 주고받을  있다.

 

<참고 - Retrofit 한글 문서 : http://devflow.github.io/retrofit-kr/>

 

 

2. 사용하기

1) 설치 및 권한 설정 

 

<!-- build.gradle  -->
...

dependencies {
    ...
    // Retrofit
    implementation 'com.squareup.retrofit2:retrofit:2.6.2' // 레트로핏 설치 (필수)
    implementation 'com.squareup.retrofit2:converter-gson:2.6.2' // 컨버터 (선택)
    implementation 'com.google.code.gson:gson:2.8.5'  //GSON (선택)
    ...
}

 

 

<!-- AndroidManifest.xml  -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.test">
    .....
    <uses-permission android:name="android.permission.INTERNET"/>
    ....
    

Http 통신을 하기 때문에 인터넷 사용에 대한 권한을 추가해 주어야 한다.

 

 

 

2) Retrofit 객체 생성하기

 

public class RetrofitFactory {

    public static Retrofit createRetrofit(String baseUrl) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        return retrofit;
    }
 }

 

Retrofit을 사용하기 위해서는 Retrofit객체를 생성해야 한다

보통 Retrofit 객체를 생성하는 메서드를 선언해두고 재사용한다.

 

Retrofit 객체를 생성하기 위해 빌더 객체를 생성해야 하고

필요한 설정 사항을 추가해서 빌드한다.

 

baseUrl은 URL 호출 시에 반복을 줄여주는 역할을 한다.

예를 들면 

kyome.tistory.com/150 호출해야 한다고 하면

보통 'kyome.tistory.com/' 까지는 고정이고

'150' 부분이 변하는 부분이기 때문에 

 ''kyome.tistory.com/'를 baseUrl로 세팅한다.

 

addConverterFactory는

HTTP 통신 시에 주고받는 데이터 형태를 

변환시켜 주는 컨버터를 지정하는 설정이다.

Gson, Jackson 등 다양하다.

 

 

 

 

3) 서비스 생성하기

 

public interface ExampleService {

    @GET("/example/info")
    Call<String> getExampleBySeq(@Query("seq") String param);
}

 

이제 Service (Retrofit 용어) 클래스를 만든다.

Retrofit에서 Service API 정의하는 인터페이스를 말한다.

 

Service는 interface로선언하기 때문에

구현할 필요는 없고 어떤 형태와

방식으로 통신을 할지를

어노테이션과 파라미터로 지정하면 된다.

(Retrofit 알아서 구현해준다)

 

Service 기본적으로 Call<T> 객체를  반환한다.

서버의 API String 반환한다고 가정하면

클라이언트는 Retrofit 통해 Call <String>를받게 것이다.

 

Call<T> 객체에 대해서는 아래에서 다룬다.

 

 

 

 

 

 

 

 

 

4) Retrofit - Service 연결하기 (Call<T> 객체얻기)

 

public class ExampleRepository {
    private ExampleRepository() {
    }
    
    // 싱클턴으로 사용
    public static ExampleRepository getInstance(){
        return ExampleRepositoryHolder.INSTANCE;
    } 
    
	public Call<String> getExampleBySeq(String seq) {
        return RetrofitFactory
        	.createRetrofit("http://10.0.2.2:8080/") // Retrofit객체 반환
        	.create(ExampleService.class)
            .getExampleBySeq(seq);
    }
}

 

Retrofit create 메서드에 Service 클래스를 넣어서

HTTP에접근할 Retrofit 객체를 만든다.

이렇게 만든 Retrofit객체를 만들었으면

클라이언트와 서버가 통신할 길을

열렸다고 있다.

Retrofit에서 Service 선언한 메서드를 호출하는

방식으로 통신의 길을 있다.

 

통신의 길이라고 표현한 이유 

더보기

 

모호하게 통신의 열었다고 표현한 이유는

Retrofit 객체를 사용해 Service에 

선언한 메서드를 호출하면 Call객체를 받는다.

 

이렇게 Call객체를 받은 것만으로 통신이되는 것이 아니라

Call객체의 enqueue 메서드를 호출해야 해당 시점에서

API 통신을 하기 때문이다.

 

실제 개발 재사용성을 높이고 

유지보수를 편하게 하기위해

 

Retrofit 생성하는

중간 클래스인 Repository 만들어 두고

필요 따른 Retrofit 생성 메서드를 저장한다.

 

 

5) Call<T> 객체 사용하기

 

 

...

ExampleRepository.getInstance()
	.getExampleBySeq(editTextSeq.getText().toString())
    	.enqueue(new Callback<String>(){
          @Override
          public void onResponse(Call<String> call, Response<String> response) {
          }

          @Override
          public void onFailure(Call<String> call, Throwable t) {
          Log.d("test", t.toString());
       	}
});

...

 

 

Call<T>은 인터페이스이다.

 

Call 인터페이스는

enqueue(Callback<T> callback); 메서드를

갖고 있어야한다.

그러니 통신을 후에 받은

Call<T> 객체는 enqueue가

구현된 상태라는 것이다.

 

이를 통해 받은 통신의 결과에 대한 처리를 있다.

Retrofit은 통신의 결과에 따라 

파라미터로 받는 Callback 의 메서드를 실행해준다.

성공시 onResponse 를 실행하고

실패  onFailure 실행한다.

 

참고로 Callback<T> 또한 인터페이스다.

void onResponse(Call<T>call,Response<T>response);

void onFailure(Call<T>call,Throwablet);

메서드가 구현을해야 사용할 수 있다.

 

 

 

 

도움이 되는 게시글이었다면 

로그인이 필요 없는 공감 버튼 꾹 눌러주세요! 

 

 

 

 

 

+ Recent posts

"여기"를 클릭하면 광고 제거.