Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

개발새발 블로그

Retrofit2 _ 기본이해 본문

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()
 
    val service = retrofit.create(WeatherInterface::class.java)
}
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 = ""
                        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형식 적용

 

 

Comments