Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

@katokonn1020

Scala、AkkaHttpで簡単に外部サーバーからGETしてくる方法

なんか手っ取り早く外部サーバーとの通信を書けないか探したのでメモ

自分で適当に作ったやつ

qiita.scala
  private def getRequest[A](uri: String): Future[String] = {
    val request = HttpRequest(GET, uri = Uri(uri))
    val res = Http().singleRequest(request)
    res.flatMap { r =>
      res.entity.dataBytes.runFold(ByteString.empty)(_ ++ _).map(_.utf8String)
    }
  }

下のところがすごい冗長感が溢れる

qiita.scala
res.entity.dataBytes.runFold(ByteString.empty)(_ ++ _).map(_.utf8String)

リファクタしたやつ

qiita.scala
  private def getRequest[A](uri: String): Future[String] = {
    val request = HttpRequest(GET, uri = Uri(uri))
    val res = Http().singleRequest(request)
    res.flatMap { r =>
      Unmarshal(r.entity).to[String]
    }
  }
qiita.scala
Unmarshal(r.entity).to[String]

Unmarshalを使えば短くかける^^
うれしい

使い方

qiita.scala
val response: Future[String] = getRequest(uri = "http:~~~~~")
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?