LoginSignup
0
0

More than 1 year has passed since last update.

【Scala】Akka-HTTPクライアントを使ってapplication/x-www-form-urlencodedのリクエストを送信する

Posted at

概要

Akka-HTTPはAkka HTTPでWeb APIに仕立てるの記事にある通り、Akkaの拡張機能の一つでWebのサーバとしてHTTPリクエストを処理できます。Akka-HTTPには外部にリクエストを投げるための機能Akka-HTTP Clientがあります。Akka-HTTP Clientの詳細については、Akka HTTP クライアントを使うを参照ください。
今回はAkka-HTTP Clientを使用して、外部にapplication/x-www-form-urlencodedのリクエストを送信する時にどうすれば良いのか、というのを書いてみたいと思います。

対応

How to include application/x-www-form-urlencoded HttpHeader in Akka-http 2.4.1?の記事にある通り、ClientのentityにFormDataのオブジェクトをセットすればいけそうです。こちらのドキュメントにある通り、FormDataはapplication/x-www-form-urlencodedに対応してるみたいです。

実装サンプル

gBizINFOという法人データを提供しているAPIに、SPARQLのクエリを投げる例をサンプルとして記載します。

CompanyRestClient.scala
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{FormData, HttpMethods, HttpRequest}
import akka.http.scaladsl.unmarshalling.Unmarshal

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.util.{Failure, Success, Try}

object CompanyRestClient {

  implicit val system = ActorSystem()
  implicit val executionContext = system.dispatcher

  val GBIZ_URL = "https://api.info.gbiz.go.jp/sparql"

  def sendRequestToGbiz(query: String)(implicit ec: ExecutionContext): Future[Try[String]] = {
    val req = HttpRequest(
      method = HttpMethods.POST,
      uri = GBIZ_URL,
      entity = FormData("query" -> query).toEntity
    )
    Http().singleRequest(req)
      .map(res => Success(Await.result(Unmarshal(res.entity).to[String], Duration.Inf))
    ).recover { case e => Failure(e) }
  }

}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0