웹사이트 검색

Retrofit Android 예제 자습서


Retrofit Android 예제 자습서에 오신 것을 환영합니다. 오늘 우리는 Square에서 개발한 Retrofit 라이브러리를 사용하여 안드로이드 애플리케이션에서 REST API 호출을 처리할 것입니다.

개조 안드로이드

Retrofit은 RESTful 웹 서비스를 보다 쉽게 사용할 수 있도록 하는 Android 및 Java용 유형 안전 REST 클라이언트입니다. Retrofit 1.x 버전에 대한 자세한 내용은 다루지 않고 이전 버전과 비교하여 많은 새로운 기능과 변경된 내부 API가 있는 Retrofit 2로 바로 이동합니다. Retrofit 2는 기본적으로 OkHttp를 네트워킹 계층으로 활용하고 그 위에 구축됩니다. Retrofit은 JSON 구조에 대해 고급에서 정의해야 하는 POJO(Plain Old Java Object)를 사용하여 JSON 응답을 자동으로 직렬화합니다. JSON을 직렬화하려면 먼저 Gson으로 변환하는 변환기가 필요합니다. build.grade 파일에 다음 종속성을 추가해야 합니다.

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

OkHttp 종속성은 이미 Retrofit 2 종속성과 함께 제공됩니다. 별도의 OkHttp 종속성을 사용하려면 다음과 같이 Retrofit 2에서 OkHttp 종속성을 제외해야 합니다.

compile ('com.squareup.retrofit2:retrofit:2.1.0') {  
  // exclude Retrofit’s OkHttp dependency module and define your own module import
  exclude module: 'okhttp'
}
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
compile 'com.squareup.okhttp3:okhttps:3.4.1'

  • logging-interceptor는 반환된 전체 응답의 로그 문자열을 생성합니다.
  • JSON을 필요한 유형으로 구문 분석하는 다른 변환기가 있습니다. 그 중 몇 가지가 아래에 나열되어 있습니다.

  1. 잭슨: com.squareup.retrofit2:converter-jackson:2.1.0
  2. 모시: com.squareup.retrofit2:converter-moshi:2.1.0
  3. Protobuf: com.squareup.retrofit2:converter-protobuf:2.1.0
  4. 와이어: com.squareup.retrofit2:converter-wire:2.1.0
  5. 단순 XML: com.squareup.retrofit2:converter-simplexml:2.1.0

AndroidManifest.xml 파일에 인터넷 접근 권한을 추가합니다.

OkHttp 인터셉터

인터셉터는 호출을 모니터링, 재작성 및 재시도할 수 있는 OkHttp에 있는 강력한 메커니즘입니다. 인터셉터는 크게 두 가지 범주로 나눌 수 있습니다.

  • 애플리케이션 인터셉터: 애플리케이션 인터셉터를 등록하려면 OkHttpClient.Builder
  • 에서 addInterceptor()를 호출해야 합니다.\n
  • 네트워크 인터셉터: 네트워크 인터셉터를 등록하려면 addInterceptor() 대신 addNetworkInterceptor()를 호출합니다.\n

Retrofit 인터페이스 설정

package com.journaldev.retrofitintro;

import com.journaldev.retrofitintro.pojo.MultipleResource;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

class APIClient {

    private static Retrofit retrofit = null;

    static Retrofit getClient() {

        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();


        retrofit = new Retrofit.Builder()
                .baseUrl("https://reqres.in")
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();



        return retrofit;
    }

}

위 코드의 getClient() 메서드는 Retrofit 인터페이스를 설정하는 동안 매번 호출됩니다. Retrofit은 각 HTTP 메서드(@GET, @POST, @PUT, @DELETE, @PATCH 또는 @HEAD)에 대한 주석 목록을 제공합니다. APIInterface.java 클래스가 어떻게 생겼는지 봅시다.

package com.journaldev.retrofitintro;

import com.journaldev.retrofitintro.pojo.MultipleResource;
import com.journaldev.retrofitintro.pojo.User;
import com.journaldev.retrofitintro.pojo.UserList;

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;

interface APIInterface {

    @GET("/api/unknown")
    Call<MultipleResource> doGetListResources();

    @POST("/api/users")
    Call<User> createUser(@Body User user);

    @GET("/api/users?")
    Call<UserList> doGetUserList(@Query("page") String page);

    @FormUrlEncoded
    @POST("/api/users?")
    Call<UserList> doCreateUserWithField(@Field("name") String name, @Field("job") String job);
}

위의 클래스에서 주석이 있는 HTTP 요청을 수행하는 몇 가지 메서드를 정의했습니다. @GET(\/api/unknown\)doGetListResources();를 호출합니다. doGetListResources()는 메서드 이름입니다. MultipleResource.java는 응답 매개변수를 해당 변수에 매핑하는 데 사용되는 응답 개체의 모델 POJO 클래스입니다. 이러한 POJO 클래스는 메서드 반환 유형으로 작동합니다. MultipleResources.java에 대한 간단한 POJO 클래스는 다음과 같습니다.

package com.journaldev.retrofitintro.pojo;

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.List;

public class MultipleResource {

    @SerializedName("page")
    public Integer page;
    @SerializedName("per_page")
    public Integer perPage;
    @SerializedName("total")
    public Integer total;
    @SerializedName("total_pages")
    public Integer totalPages;
    @SerializedName("data")
    public List<Datum> data = null;

    public class Datum {

        @SerializedName("id")
        public Integer id;
        @SerializedName("name")
        public String name;
        @SerializedName("year")
        public Integer year;
        @SerializedName("pantone_value")
        public String pantoneValue;

    }
}

  • @Body - Java 개체를 요청 본문으로 보냅니다.
  • @Url - 동적 URL을 사용합니다.
  • @Query - 유형을 설명하는 @Query와 쿼리 매개변수 이름을 사용하여 메서드 매개변수를 간단히 추가할 수 있습니다. 쿼리를 URL 인코딩하려면 다음 형식을 사용하십시오. @Query(value = \auth_token\,encoded = true) String auth_token
  • @Field - form-urlencoded로 데이터를 보냅니다. 이를 위해서는 메소드와 함께 첨부된 @FormUrlEncoded 주석이 필요합니다. @Field 매개변수는 POST
  • 에서만 작동합니다.\n

참고: @Query 대신 null 값을 전달하십시오.

Retrofit Android 예제 프로젝트 구조

package com.journaldev.retrofitintro.pojo;

import com.google.gson.annotations.SerializedName;

public class User {

    @SerializedName("name")
    public String name;
    @SerializedName("job")
    public String job;
    @SerializedName("id")
    public String id;
    @SerializedName("createdAt")
    public String createdAt;

    public User(String name, String job) {
        this.name = name;
        this.job = job;
    }


}

위의 클래스는 createUser() 메서드 UserList.java에 대한 응답 본문을 만드는 데 사용됩니다.

package com.journaldev.retrofitintro.pojo;

import com.google.gson.annotations.SerializedName;

import java.util.ArrayList;
import java.util.List;

public class UserList {

    @SerializedName("page")
    public Integer page;
    @SerializedName("per_page")
    public Integer perPage;
    @SerializedName("total")
    public Integer total;
    @SerializedName("total_pages")
    public Integer totalPages;
    @SerializedName("data")
    public List<Datum> data = new ArrayList();

    public class Datum {

        @SerializedName("id")
        public Integer id;
        @SerializedName("first_name")
        public String first_name;
        @SerializedName("last_name")
        public String last_name;
        @SerializedName("avatar")
        public String avatar;

    }
}

CreateUserResponse.java

package com.journaldev.retrofitintro.pojo;

import com.google.gson.annotations.SerializedName;

public class CreateUserResponse {

    @SerializedName("name")
    public String name;
    @SerializedName("job")
    public String job;
    @SerializedName("id")
    public String id;
    @SerializedName("createdAt")
    public String createdAt;
}

MainActivity.java는 Interface 클래스에 정의된 각 API 엔드포인트를 호출하고 Toast/TextView에 각 필드를 표시하는 곳입니다.

package com.journaldev.retrofitintro;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.journaldev.retrofitintro.pojo.CreateUserResponse;
import com.journaldev.retrofitintro.pojo.MultipleResource;
import com.journaldev.retrofitintro.pojo.User;
import com.journaldev.retrofitintro.pojo.UserList;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    TextView responseText;
    APIInterface apiInterface;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        responseText = (TextView) findViewById(R.id.responseText);
        apiInterface = APIClient.getClient().create(APIInterface.class);


        /**
         GET List Resources
         **/
        Call<MultipleResource> call = apiInterface.doGetListResources();
        call.enqueue(new Callback<MultipleResource>() {
            @Override
            public void onResponse(Call<MultipleResource> call, Response<MultipleResource> response) {


                Log.d("TAG",response.code()+"");

                String displayResponse = "";

                MultipleResource resource = response.body();
                Integer text = resource.page;
                Integer total = resource.total;
                Integer totalPages = resource.totalPages;
                List<MultipleResource.Datum> datumList = resource.data;

                displayResponse += text + " Page\n" + total + " Total\n" + totalPages + " Total Pages\n";

                for (MultipleResource.Datum datum : datumList) {
                    displayResponse += datum.id + " " + datum.name + " " + datum.pantoneValue + " " + datum.year + "\n";
                }

                responseText.setText(displayResponse);

            }

            @Override
            public void onFailure(Call<MultipleResource> call, Throwable t) {
                call.cancel();
            }
        });

        /**
         Create new user
         **/
        User user = new User("morpheus", "leader");
        Call<User> call1 = apiInterface.createUser(user);
        call1.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                User user1 = response.body();

                Toast.makeText(getApplicationContext(), user1.name + " " + user1.job + " " + user1.id + " " + user1.createdAt, Toast.LENGTH_SHORT).show();

            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                call.cancel();
            }
        });

        /**
         GET List Users
         **/
        Call<UserList> call2 = apiInterface.doGetUserList("2");
        call2.enqueue(new Callback<UserList>() {
            @Override
            public void onResponse(Call<UserList> call, Response<UserList> response) {

                UserList userList = response.body();
                Integer text = userList.page;
                Integer total = userList.total;
                Integer totalPages = userList.totalPages;
                List<UserList.Datum> datumList = userList.data;
                Toast.makeText(getApplicationContext(), text + " page\n" + total + " total\n" + totalPages + " totalPages\n", Toast.LENGTH_SHORT).show();

                for (UserList.Datum datum : datumList) {
                    Toast.makeText(getApplicationContext(), "id : " + datum.id + " name: " + datum.first_name + " " + datum.last_name + " avatar: " + datum.avatar, Toast.LENGTH_SHORT).show();
                }


            }

            @Override
            public void onFailure(Call<UserList> call, Throwable t) {
                call.cancel();
            }
        });


        /**
         POST name and job Url encoded.
         **/
        Call<UserList> call3 = apiInterface.doCreateUserWithField("morpheus","leader");
        call3.enqueue(new Callback<UserList>() {
            @Override
            public void onResponse(Call<UserList> call, Response<UserList> response) {
                UserList userList = response.body();
                Integer text = userList.page;
                Integer total = userList.total;
                Integer totalPages = userList.totalPages;
                List<UserList.Datum> datumList = userList.data;
                Toast.makeText(getApplicationContext(), text + " page\n" + total + " total\n" + totalPages + " totalPages\n", Toast.LENGTH_SHORT).show();

                for (UserList.Datum datum : datumList) {
                    Toast.makeText(getApplicationContext(), "id : " + datum.id + " name: " + datum.first_name + " " + datum.last_name + " avatar: " + datum.avatar, Toast.LENGTH_SHORT).show();
                }

            }

            @Override
            public void onFailure(Call<UserList> call, Throwable t) {
                call.cancel();
            }
        });

    }
}

apiInterface = APIClient.getClient().create(APIInterface.class);는 APIClient를 인스턴스화하는 데 사용됩니다. Model 클래스를 응답에 매핑하기 위해 다음을 사용합니다. MultipleResource resource = response.body(); 애플리케이션을 실행하면 각 엔드포인트를 호출하고 이에 따라 Toast 메시지를 표시합니다. 이것으로 Retrofit Android 예제 자습서가 끝납니다. 아래 링크에서 Android Retrofit 예제 프로젝트를 다운로드할 수 있습니다.

Retrofit Android 예제 프로젝트 다운로드