Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

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

自分で適当に作ったやつ

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:~~~~~")
katokonn1020
Scalaエンジニアやってます
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした