본문 바로가기

안드로이드 심심풀이/응용

[안드로이드 스튜디오] Retrofit 라이브러리 예제

반응형

안녕하세요! 오늘은 Retrofit을 이용한 간단한 통신연결을 해봅니다!

 

Retrofit은 Square에서 제공하고 있는 Http 통신을 위한 라이브러리 입니다!

 

과거에는 동기를 맞추는 방식으로 통신을 연결했는데요. 이제는 Retrofit을 통해 간단하게 통신을 연결할 수 있습니다!


1. 먼저 Retrifit 클래스에 Uri를 넣어서 선언해 줍니다!

Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();

여기서 중요한부분은 .addConverterFactory(GsonConverterFactory.create())을 해주지 않으면 오류가 날수가 있습니다!

java.lang.IllegalArgumentException: Unable to create converter for java.util.List<com.example.retrofit.Repo> 
        for method GitHubService.listRepos

이런 오류가 나온다면 저 부분을 제대로 적어주셨는지 확인해 주시면 됩니다!

 

2. GithubService interface를 생성해 줍니다! 

public interface GithubService {
        @GET("users/{user}/repos")
        Call<List<Repo>> listRepos(@Path("user") String user);
}

저는 따로 파일을 만들어서 선언헀지만 1번이 있는 부분에 같이 선언하셔도 상관없습니다!

 

3. retrofit을 통해 불러온 데이터를 저장하고 불러올 클래스를 만들어줍니다!

class Repo {
    int id;
    String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

 

4. GitHubService를 1번부분 아래에 선언해주시고 retrofit을 넣어 줍니다!

GitHubService service = retrofit.create(GitHubService.class);

Call<List<Repo>> repos = service.listRepos("octocat");

그 후 Call객체에 service를 넣어주도록 합니다!

"octocat"부분은 자신의 github 이름을 적어주셔도 됩니다!

 

5. 마지막으로 enqueue를 통해 통신이 제대로 연결되었는지 확인합니다!

    repos.enqueue(new Callback<List<Repo>>() {
        @Override
        public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
            Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT).show();
            content.setText(response.body().toString());
        }

        @Override
        public void onFailure(Call<List<Repo>> call, Throwable t) {
            Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_SHORT).show();
        }
    });

결과 화면

 


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final TextView content;
        content=(TextView)findViewById(R.id.content);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        GitHubService service = retrofit.create(GitHubService.class);

        Call<List<Repo>> repos = service.listRepos("octocat");

        repos.enqueue(new Callback<List<Repo>>() {
            @Override
            public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
                Toast.makeText(MainActivity.this, response.body().toString(), Toast.LENGTH_SHORT).show();
                content.setText(response.body().toString());
            }

            @Override
            public void onFailure(Call<List<Repo>> call, Throwable t) {
                Toast.makeText(MainActivity.this, t.toString(), Toast.LENGTH_SHORT).show();
            }
        });

    }
}

전체 코드입니다!

감사합니다~

반응형