생각자유의 안드로이드 이야기

Retrofit 기본 기능에 대해서 알아보자(날씨를 조회하는 RestAPI) 본문

Android/Retrofit

Retrofit 기본 기능에 대해서 알아보자(날씨를 조회하는 RestAPI)

생각자유 2016. 2. 2. 17:01
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.


소소하게 Youtube채널을 개성하였습니다.

좋아요 및 구독 부탁드리겠습니다. (곧 안드로이드 관련 많은 자료들을 올릴 예정입니다.)

https://www.youtube.com/channel/UCwgElJMunsiDF8P2UOzjx2g/




우선 조대협님께서 작성하신 

[REST API를 이용하여, 날씨를 조회하는 간단한 애플리케이션 만들기]

http://bcho.tistory.com/1050


를 Retrofit으로 변경을 해보겠습니다.


-> 제가 작성한 코드를 Github에 올려두었습니다. https://github.com/Myeongwon-Kang/GetWeather


일단 조대협님께서 작성하신 코드는 일반적인 HttpUrlConnection, gson, AsynsTask등을 사용하였는데 Retrofit을 사용하면 조금더 편안하게(?)작성을 가능합니다.


Retrofit

A type-safe HTTP client for Android and Java


Retrofit은 https://squareup.com에서 만든Http라이브러리 입니다.


일단 가장 많이 사용하는 이유는 성능상에 이점과 비동기처리 지원 기타 여러가지 자질구질한것들은 대부분 깔끔하게 처리를 해주기 떄문에


갈수록 인기가 많아지고 있는 Http통신 라이브러리 입니다.


1. 샘플용 APIkey를 사용해서 받아와야할 JSON데이터를 살펴 보겠습니다.

http://api.openweathermap.org/data/2.5/weather?lat=37&lon=127&appid=44db6a862fba0b067b1930da0d769e98
{
"coord" : {
"lon" : 127,
"lat" : 37
},
"weather" : [{
"id" : 800,
"main" : "Clear",
"description" : "sky is clear",
"icon" : "01d"
}
],
"base" : "stations",
"main" : {
"temp" : 273.57,
"pressure" : 1026,
"humidity" : 24,
"temp_min" : 272.15,
"temp_max" : 274.15
},
"visibility" : 10000,
"wind" : {
"speed" : 1.5,
"deg" : 180
},
"clouds" : {
"all" : 1
},
"dt" : 1454397600,
"sys" : {
"type" : 1,
"id" : 8519,
"message" : 0.0117,
"country" : "KR",
"sunrise" : 1454366056,
"sunset" : 1454403446
},
"id" : 1838431,
"name" : "Pyeong",
"cod" : 200
}

어떤 데이터들이 있는지 확인 했으니 이제 JSON데이터를 받아줄 Repo Class를 만들어 봅시다.

0. 준비사항
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

1. Repo Class
public class Repo {
Main main;

public Main getMain() {
return main;
}
}
public class Main {
Double temp;
Integer pressure;
Integer humidity;
Double temp_min;
Double temp_max;


public Double getTemp() {
return temp;
}

public Integer getPressure() {
return pressure;
}

public Integer getHumidity() {
return humidity;
}

public Double getTemp_min() {
return temp_min;
}

public Double getTemp_max() {
return temp_max;
}
}

2. 인터페이스 선언하기

public interface ApiInterface {
@GET("/data/2.5/weather")
Call<Repo> repo(@Query("appid") String appid, @Query("lat") double lat, @Query("lon") double lon);
}

Retrofit의 경우 서술형으로 작성을 해주어서 편리합니다. 당연히 @post, @put, @delete등을 지원합니다.



3. 인터페이스 구현

@Bind(R.id.tem)
TextView tem;
@Bind(R.id.getWeatherBtn)
Button getWeatherBtn;
@Bind(R.id.tvLatitude)
TextView tvLatitude;
@Bind(R.id.tvLongtitude)
TextView tvLongtitude;
@Bind(R.id.lat)
EditText mlat;
@Bind(R.id.lon)
EditText mlon;

@OnClick(R.id.getWeatherBtn)
public void setGetWeatherBtn(View view){

String lat= mlat.getText().toString();
String lot = mlon.getText().toString();

Retrofit client = new Retrofit.Builder().baseUrl("http://api.openweathermap.org").addConverterFactory(GsonConverterFactory.create()).build();

ApiInterface service = client.create(ApiInterface.class);
Call<Repo> call = service.repo(API_KEY(개인적으로 발급 받으세요.), Double.valueOf(lat), Double.valueOf(lot));
call.enqueue(new Callback<Repo>() {
@Override
public void onResponse(Response<Repo> response) {
if (response.isSuccess()) {
Repo repo = response.body();
tem.setText(String.valueOf(repo.getMain().getTemp()));
} else {

}
}

@Override
public void onFailure(Throwable t) {
}
});
}

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}

4. 결과




Comments