kotlin
Retrofit2 _ 기본이해
SeanBlog
2019. 12. 12. 12:24
class WeatherConnection {
val baseUrl = "https://api.openweathermap.org/"
val retrofit = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
interface WeatherInterface {
@POST("data/2.5/{type}")
fun getWeather2(@Path("type") type : String ,@Query("id") id:String, @Query("APPID") APPID:String) : Call<ResWeatherData>
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
- @Path : @POST에 {type} 란에 들어갈 부분
- @Query : @POST 이후 들어갈 변수들에 이름과 값
private fun setRealTime(retrofitconnection: WeatherConnection) {
val call: Call<ResWeatherData> = retrofitconnection.service.getWeather2("weather","1835841", "472bc4b8b7c94d954600861c857a2ca9")
call.enqueue(object : Callback<ResWeatherData> {
override fun onResponse(call: Call<ResWeatherData>, response: Response<ResWeatherData>) {
if (response.isSuccessful) {
val body = response.body()
body?.let {
Log.d("asdf", Gson().toJson(body))
binding.textView.text = Gson().toJson(body)
}
}
}
override fun onFailure(call: Call<ResWeatherData>, t: Throwable) {
Log.d("this is error", t.message)
}
}
)
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|
※ Gson
val data = WeatherData(weather = "asdf",
windSpeed = 5,
cloud = 3)
Log.d("qqqq","" + Gson().toJson(data))
val qqq = """
{"cloud":3,"weather":"asdf","windSpeed":5}
"""
val data2 = Gson().fromJson(qqq,WeatherData::class.java)
|
Tip. """ 3개는 안쪽에 " 같은 인자를 무시하고 String형식 적용