모르는게 많은 개발자

[안드로이드] Retrofit2 간단 예제 본문

안드로이드

[안드로이드] Retrofit2 간단 예제

Awdsd 2020. 4. 9. 02:40
반응형

이번 포스팅에서는 안드로이드에서 Rest API 통신을 하기위한 Retrofit2 라이브러리 사용법을 알아보려한다.

 

1. API 데이터 준비

age, detail, patientid, sex로 이루어진 json 데이터

 

key parameter를 출력하는 API

 

2. 기본 설정

build.gradle에 retrofit2 추가
permisson 허용
MainActivity에 API 데이터출력을 위한 TextView추가 

 

3. API 데이터 저장할 클래스

 

데이터 클래스의 변수를 설정할 때 Json데이터의 속성 이름으로 바인딩 되기 때문에 Json데이터의 속성 이름과 클래스 변수 이름을 맞춰줘야한다.

public class PatientData {
    private int age;
    private String detail;
    private String patientid;
    private String sex;

    public int getAge() {
        return age;
    }

    public String getDetail() {
        return detail;
    }

    public String getPatientId() {
        return patientid;
    }

    public String getSex() {
        return sex;
    }

    @Override
    public String toString() {
        return "PatientData{" +
                "age=" + age +
                ", detail='" + detail + '\'' +
                ", patientid='" + patientid + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}
public class Data {
    private String key;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }
}

 

 

 

 

4. API Service

@GET은 리소스를 써준다.

@Query에는 parameter이름을 써준다. 이렇게 되면 total리소스에 key파라미터 값을 요청하겠다는 뜻이다.

public interface JsonApi {
    @GET("patient")
    Call<List<PatientData>> getPatient();

    @GET("total")
    Call<Data> getData(@Query("key") String key);
}

 

5. API 호출

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Retrofit retrofit;
    JsonApi jsonApi;
    Call<List<PatientData>> call;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.123.106:80/")	//베이스 url등록
                .addConverterFactory(GsonConverterFactory.create())	//JSON -> 자바객채변환
                .build();
                
        jsonApi = retrofit.create(JsonApi.class);
        
        call2 = jsonApi.getData("awd");    //key parameter에 awd 전달
        
        //API 호출 
        call2.enqueue(new Callback<Data>() {	//비동기로 실행되어 콜백으로 앱으로 알려줌
            //API Reponse 됐을 경우 호출 단, 404, 500 error에도 호출
            @Override
            public void onResponse(Call<Data> call, Response<Data> response) {
                //응답이 성공적으로 됐을경우
                if(response.isSuccessful()) {
                    textView = (TextView) findViewById(R.id.text);
                    //자바 객체로 변환된 JSON데이터 저장
                    Data data = response.body();
                    textView.setText(data.getKey());
                }
            }
            //서버와 통신중 네트워크 예외 발생시 호출
            @Override
            public void onFailure(Call<Data> call, Throwable t) {

            }
        });
    }
}

 

 

결과 

 

public class MainActivity extends AppCompatActivity {
    TextView textView;
    Retrofit retrofit;
    JsonApi jsonApi;
    Call<List<PatientData>> call;
    Call<Data> call2;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.123.106:80/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        jsonApi = retrofit.create(JsonApi.class);

        call = jsonApi.getPatient();
        call.enqueue(new Callback<List<PatientData>>() {
            @Override
            public void onResponse(Call<List<PatientData>> call, Response<List<PatientData>> response) {
                if(response.isSuccessful()) {
                    textView = (TextView)findViewById(R.id.text);
                    textView.setText(response.body().toString());
                }
            }

            @Override
            public void onFailure(Call<List<PatientData>> call, Throwable t) {

            }
        });
    }
}

age, detail, patientid, sex로 이루어진       json 데이터 출력

 

반응형
Comments