로또 open api 레트로핏 예제
로또 오픈 api를 레트로핏을 활용하여 안드로이드에서 데이터를 가져오는 예제.
사용 java 파일
1. 데이터 오브젝트 - LottoData.java
2. 레트로핏 인터페이스 - retrofitInterface
3. 통신 호출 함수 - retro()
---
<uses-permission android:name="android.permission.INTERNET"/>
매니패스트에 추가 필요.
1.
public class LottoData {
String totSellamnt;
String returnValue;
String drwNoDate;
String firstWinamnt;
String firstPrzwnerCo;
String firstAccumamnt;
String drwtNo1;
String drwtNo2;
String drwtNo3;
String drwtNo4;
String drwtNo5;
String drwtNo6;
String bnusNo;
public String getTotSellamnt() { return totSellamnt; }
public String getReturnValue() { return returnValue; }
public String getDrwNoDate() { return drwNoDate; }
public String getFirstWinamnt() { return firstWinamnt; }
public String getFirstPrzwnerCo() { return firstPrzwnerCo; }
public String getFirstAccumamnt() { return firstAccumamnt; }
public String getDrwtNo1() { return drwtNo1; }
public String getDrwtNo2() { return drwtNo2; }
public String getDrwtNo3() { return drwtNo3; }
public String getDrwtNo4() { return drwtNo4; }
public String getDrwtNo5() { return drwtNo5; }
public String getDrwtNo6() { return drwtNo6; }
public String getBnusNo() { return bnusNo; }
}
2.
public interface retrofitInterface {
String LottoUrl = "https://www.nlotto.co.kr";
@GET("/common.do")
Call getLotto(@Query("method") String method, @Query("drwNo") String drwNum);
}
3.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(retrofitInterface.LottoUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
retrofitInterface retrofitExService = retrofit.create(retrofitInterface.class);
retrofitExService.getLotto("getLottoNumber","1").enqueue(new Callback() {
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
if (response.isSuccessful()) {
LottoData body = response.body();
if (body != null) {
Log.d(TAG,"추첨일 " +body.drwNoDate);
}
}
}
@Override
public void onFailure(@NonNull Call call, @NonNull Throwable t) {
Log.d(TAG,"fail");
}
});
로또 open api의 호출 url는 https://www.nlotto.co.kr/common.do?method=getLottoNumber&drwNo=호출번호
이다.
url에 보면 쿼리 스트링이 ("?") 존재하기 때문에 그에 따른 값을 매핑시키기 위하여
인터페이스에 getlotto 보면 method 및 drwNo를 파라미터 값으로 넣어줌
그와 마찬가지로 호출부분에서도 위와 같은 값을 넣어줌
- 번외 -
만일 위와 같지 쿼리 스트링이 존재하지 않는 url은
/***
https://www.naver.com/posts/2 <- 예를 들면 이런 . url?
***/
url = https://www.naver.com;
@GET("/posts/{data}")
Call<LottoData> getData(@Path("data") String userId);
위와 같은 코드로 적용 시킬 수 있다.