在JAK Http中将JSON POST到端点

时间:2018-03-09 14:43:03

标签: scala akka-http

我正在尝试创建HttpRequest并尝试将json提交到endPoint,我的其余服务是使用akka-http编写的

  case class JobInfo(jobName: String,
                   appId: Option[String] = None,
                   status: Option[String] = None,
                   modify_date: Option[Long] = None)

object Test extends App{

import HttpMethods._
  val fieldList = List(
    ("jobName",Json.fromString("TestJobA")),
    ("appId",Json.fromString("1234")),
    ("status",Json.fromString("Running")),
    ("modify_date",Json.fromLong(DateTime.now.getMillis))
  )
  val json = Json.fromFields(fieldList)

  val endPoint = Uri.from(scheme = "http",
    host = "0.0.0.0",
    port = 7000,
    path = s"/updateJobDetails/").toString()

  val requestEntity = HttpEntity(MediaTypes.`application/json`, json.toString)
//  val postRequest1 = HttpRequest.POST("/receive").withEntity(requestEntity)
  HttpRequest(POST,"http://0.0.0.0:7000/updateJobDetails",entity = requestEntity)

} 

但这似乎不起作用, 早些时候我用喷雾做了同样的事情

  val pipe: HttpRequest => Future[HttpResponse] = sendReceive
          val json =
            s"""{
               |  "jobName" : "jobA",
               |  "appId" :"${jobInfo.appId.getOrElse("Not Set")}",
               |  "status" :"${jobInfo.status.getOrElse("Not Set")}",
               |  "modify_date" :${DateTime.now.getMillis}
               |}""".stripMargin.parseJson.asJsObject()

          //Rest EndPoint for JobDetails updation.
          val endPoint = Uri.from(scheme = "http",
            host ="0.0.0.0",
            port = 7000,
            path = s"/updateJobDetails").toString()

          val response = pipe(Put(endPoint, json))

任何人都可以帮我纠正我所缺少的内容

1 个答案:

答案 0 :(得分:1)

当你说"没有工作"还提供了您收到的错误消息。

无论如何,从您上面发布的代码中。你正在建设未来,但你不是在等待它完成。

下面的代码显示了如何构建Future然后等待它完成。

object Client {
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    // needed for the future flatMap/onComplete in the end
    implicit val executionContext = system.dispatcher

    val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(uri = "http://akka.io"))

    responseFuture
      .onComplete {
        case Success(res) => println(res)
        case Failure(_)   => sys.error("something wrong")
      }
    Await.result(responseFuture, Duration.Inf)
  }
}