sbt by example中metaweather.com公共API失效的解决办法 --- 替换另一个公共API

跟着sbt官方网站的教程做一遍,发现其中用到了https://www.metaweather.com/api/location这个公共API。很不幸的是,它已经失效了,现根据原文(地址在此),稍加改编提供两个scala代码片段,使得其可以运行,继续完成该页教程:

Use Scala REPL部分可以用来替代的Scala代码:

import scala.concurrent._, duration._
import gigahorse._, support.okhttp.Gigahorse
import play.api.libs.json._
Gigahorse.withHttp(Gigahorse.config) { http =>
  val baseUrl = "https://api.coronavirus.data.gov.uk"
  val rCorona = Gigahorse.url(baseUrl + "/v1/data").get.
    addQueryString("filters" -> "areaType=nation;areaName=england").
    addQueryString("structure" -> "{%22date%22:%22date%22,%22newCases%22:%22newCasesByPublishDate%22}")
  val fCorona = http.run(rCorona, Gigahorse.asString)
  val corona = Await.result(fCorona, 10.seconds)
  val data = (Json.parse(corona) \ "data").as[JsValue]
  (Json.prettyPrint)(data)
}

  

Parse JSON using Play JSON部分可以用来替代的Scala代码:

我自作了两点聪明:

  1. 把原文中的Weather.scala改了名字成为Corona.scala;
  2. 把原文中Hello.scala中引用的core.Weather及其包含的方法改成了core.Corona及其包含的方法。

Corona.scala

package example.core

import gigahorse._, support.okhttp.Gigahorse
import scala.concurrent._, duration._
import play.api.libs.json._

object Corona {
  lazy val http = Gigahorse.http(Gigahorse.config)

  def deathCases: Future[String] = {
    val baseUrl = "https://api.coronavirus.data.gov.uk"
    val rCorona = Gigahorse.url(baseUrl + "/v1/data").get.
      addQueryString("filters" -> "areaType=nation;areaName=england").
      addQueryString("structure" -> "{%22date%22:%22date%22,%22newCases%22:%22newCasesByPublishDate%22}")
    import ExecutionContext.Implicits.global
    for {
      fCorona <- http.run(rCorona, parse)
      fData = (fCorona \ "data").get
    } yield (fData \\ "newCases")(0).toString
  }

  private def parse = Gigahorse.asString andThen Json.parse
}

Hello.scala

package example

import scala.concurrent._, duration._
import core.Corona

object Hello extends App {
  val deathCases = Await.result(Corona.deathCases, 10.seconds)
  println(s"Hello! The new death cases is $deathCases. ")
  Corona.http.close()
}

  

按照原文的步骤可以继续成功执行下去。

谢谢

 

posted @ 2021-04-30 17:48  夏花与星空  阅读(125)  评论(0)    收藏  举报