如何调用POST到另一个服务并接收json数据

时间:2018-12-22 18:40:25

标签: scala akka akka-http

我有两个Akka HTTP服务(服务1和服务2)。一个需要与另一个进行通信。

服务2提供了一个POST端点/lastname,它接收像这样的{name: "doe"}的json负载并返回{"returnVal":false}{"returnVal":true}

问题

服务1如何连接到它,发送json负载并获取布尔响应?

我在下面尝试:

val responseFuture: Future[HttpResponse] = Http().singleRequest(
  HttpRequest(
    uri = s"$host:$port/my/endpoint")
    entity = HttpEntity(MediaTypes.`application/json`, method = HttpMethods.POST)
)

但是我不知道要随请求一起发送json数据{name: "doe"}

1 个答案:

答案 0 :(得分:0)

要创建JSON,您需要使用json marshaller,例如upicklespray-json。我使用spray json将scala类转换为json,反之亦然。我假设Service2将{“ name”:“ paul”}作为请求并返回{“ exist”:true}作为响应。

import spray.json.{DefaultJsonProtocol, RootJsonFormat}


case class NameExistsRequest(name: String)
case class NameExistsResponse(exist: Boolean)

object ServiceJsonProtocolNameExists extends DefaultJsonProtocol{
  implicit val nameExistsRequestJF: RootJsonFormat[NameExistsRequest] = jsonFormat1(NameExistsRequest)
  implicit val nameExistsResponseJF: RootJsonFormat[NameExistsResponse] = jsonFormat1(NameExistsResponse)
}


  case object NameExistsError extends RuntimeException with NoStackTrace

  case object InternalError extends RuntimeException with NoStackTrace

  def sendNameExistsRequest(): Future[NameExistsResponse] = {
    import ServiceJsonProtocolNameExists._
    import spray.json._

    val endpoint = "http://your-endpoint"
    val request = NameExistsRequest("paul")
    val httpRequest = HttpRequest(
      method = HttpMethods.POST,
      uri = Uri(endpoint),
      headers = List.empty,
      entity = HttpEntity(ContentTypes.`application/json`, request.toJson.toString)
    )


    Http().singleRequest(httpRequest).transformWith {
      case Success(response) =>
        response match {
          case HttpResponse(StatusCodes.OK, _, entity, _) =>
            Unmarshal(entity).to[String].map {content =>
              content.parseJson.convertTo[NameExistsResponse]
            }
          case res =>
            println("failure response: " + res)
            Future.failed(NameExistsError)
        }
      case Failure(f) =>
        println("failed to send request, caused by: " + f)
        Future.failed(InternalError)
    }

  }

哪个NameExistsRequest代表您的请求,我们使用toJson方法将其转换为json,而NameExistsResponse代表由Service2返回的响应。我们使用Unmarshall和convertTo将json转换为scala类。