Ana içeriğe atla

Groovy Script

import groovy.json.JsonSlurper

def location = 'Stockholm, Sweden'
def connection = new URL("https://query.yahooapis.com/v1/public/yql?q=" + 
    URLEncoder.encode("select item " +
    "from weather.forecast where woeid in " +
    "(select woeid from geo.places(1) " +
    "where text='$location')", 'UTF-8' ) )
    .openConnection() as HttpURLConnection

// set some headers
connection.setRequestProperty( 'User-Agent', 'groovy-2.4.4' )
connection.setRequestProperty( 'Accept', 'application/json' )

if ( connection.responseCode == 200 ) {
    // get the JSON response
    def json = connection.inputStream.withCloseable { inStream ->
        new JsonSlurper().parse( inStream as InputStream )
    }
    
    // extract some data from the JSON, printing a report
    def item = json.query.results.channel.item
    
    requestHeaderMapToTargetAPI.put("title",item.title)
    requestHeaderMapToTargetAPI.put("Temperature","${item.condition?.temp}")
    requestHeaderMapToTargetAPI.put("Condition","${item.condition?.text}")
    
    requestUrlParamMapToTargetAPI.put("title",item.title)
    requestUrlParamMapToTargetAPI.put("Temperature","${item.condition?.temp}")
    requestUrlParamMapToTargetAPI.put("Condition","${item.condition?.text}")
    
    bodyText= 'title:'+ item.title + ', temp:' + "${item.condition?.temp}" + ", text:" + "${item.condition?.text}"
    
    // show some forecasts
    def forecast= 'Forecasts:'
    item.forecast.each { f ->
        forecast += ' * ${f.date} - Low: ${f.low}, High: ${f.high}, Condition: ${f.text}'
    }
} else {
    requestHeaderMapToTargetAPI.put("responseCode",connection.responseCode)
    requestHeaderMapToTargetAPI.put("responseText",connection.inputStream.text)
    requestUrlParamMapToTargetAPI.put("responseCode",connection.responseCode)
    requestUrlParamMapToTargetAPI.put("responseText",connection.inputStream.text)
    bodyText='title:'+ item.title + ', code:' + connection.responseCode +", text:" + connection.inputStream.text
}

Açıklama

Bu script şu işlemleri gerçekleştirir:
  1. API Çağrısı: Yahoo Weather API’sine HTTP isteği yapılır
  2. JSON Parse: JSON yanıtı parse edilir
  3. Veri Çıkarma: Hava durumu bilgileri çıkarılır
  4. Veri İletimi: Bu bilgiler header, URL parametresi veya body olarak backend’e iletilir
  5. Hata Yönetimi: Hata durumunda hata bilgileri iletilir
Bu script, request hattında (Request Policy) çalıştırılmalıdır çünkü requestHeaderMapToTargetAPI ve requestUrlParamMapToTargetAPI değişkenlerini kullanmaktadır.