기상청 단기 날씨 API(kotlin)

박재원·2024년 3월 11일
0

TIL

목록 보기
45/50
post-thumbnail
post-custom-banner

WeatherInterface

import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query


interface WeatherInterface {
    // getVilageFcst : 동네 예보 조회
    @GET("getVilageFcst?serviceKey=API키")

    fun getWeather(@Query("dataType") dataType : String,
                   @Query("numOfRows") numOfRows : Int,
                   @Query("pageNo") pageNo : Int,
                   @Query("base_date") baseDate : String,
                   @Query("base_time") baseTime : String,
                   @Query("nx") nx : String,
                   @Query("ny") ny : String)
            : Call<weather>
}

WeatherClient

import com.google.gson.GsonBuilder
import com.twoday.todaytrip.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

object WeatherClient {
    private const val WEATHER_BASE_URL = "http://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/"
    private val gson = GsonBuilder().setLenient().create()
    private fun createOkHttpClient(): OkHttpClient {
        val interceptor = HttpLoggingInterceptor()

        if (BuildConfig.DEBUG)
            interceptor.level = HttpLoggingInterceptor.Level.BODY
        else
            interceptor.level = HttpLoggingInterceptor.Level.NONE

        return OkHttpClient.Builder()
            .connectTimeout(20, TimeUnit.SECONDS)
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20, TimeUnit.SECONDS)
            .addNetworkInterceptor(interceptor)
            .build()
    }

    private val weatherRetrofit = Retrofit.Builder()
        .baseUrl(WEATHER_BASE_URL).addConverterFactory(GsonConverterFactory.create())
        .client(createOkHttpClient())
        .build()

    val weatherNetWork: WeatherInterface = weatherRetrofit.create(WeatherInterface::class.java)
}

WeatherDTO

package com.twoday.todaytrip.weather

import com.google.gson.annotations.SerializedName

data class weather(
    @SerializedName("response")
    val response: Response
)
data class Response(
    @SerializedName("body")
    val body: Body,
    @SerializedName("header")
    val header: Header
)
data class Header(
    @SerializedName("resultCode")
    val resultCode: String,
    @SerializedName("resultMsg")
    val resultMsg: String
)
data class Body(
    @SerializedName("dataType")
    val dataType: String,
    @SerializedName("items")
    val items: Items,
    @SerializedName("numOfRows")
    val numOfRows: Int,
    @SerializedName("pageNo")
    val pageNo: Int,
    @SerializedName("totalCount")
    val totalCount: Int
)
data class Items(
    @SerializedName("item")
    val item: List<Item>
)
data class Item(
    @SerializedName("baseDate")
    val baseDate: String,
    @SerializedName("baseTime")
    val baseTime: String,
    @SerializedName("category")
    val category: String,
    @SerializedName("fcstDate")
    val fcstDate: String,
    @SerializedName("fcstTime")
    val fcstTime: String,
    @SerializedName("fcstValue")
    val fcstValue: String,
    @SerializedName("nx")
    val nx: Int,
    @SerializedName("ny")
    val ny: Int
)

weatherInfo()

WeatherClient.weatherNetWork.getWeather(
            dataType = "JSON",
            numOfRows = 12,
            pageNo = 1,
            baseDate = baseDate,
            baseTime = baseTime,
            nx = latitude,
            ny = longitude
        ).enqueue(object : retrofit2.Callback<weather> {
            override fun onResponse(call: Call<weather>, response: Response<weather>) {
                if (response.isSuccessful) {
                    val it: List<Item> = response.body()?.response?.body?.items?.item ?: return
                    var temp = ""
                    var sky = ""
                    var rainType = ""

                    it.forEach { item ->
                        when (item.category) {
                            "SKY" -> sky = item.fcstValue
                            "TMP" -> temp = item.fcstValue
                            "PTY" -> rainType = item.fcstValue
                        }
                    }
                    Log.d("iop", sky)
                    setWeather(rainType, sky, temp)
                }
            }

            override fun onFailure(call: Call<weather>, t: Throwable) {
                Log.d("api fail", t.message.toString())
            }
        })
post-custom-banner

0개의 댓글