发布到akka-http服务器时,“预期列表为JsArray”

时间:2017-02-08 19:26:59

标签: akka-http spray-json httpie

我正在尝试在此处创建Orders / Items应用程序的轻微变体: https://github.com/akka/akka-http/blob/master/docs/src/test/scala/docs/http/scaladsl/SprayJsonExampleSpec.scala#L51

我正在使用httpie连接到服务器,命令是:

http POST http://localhost:8080/post_an_order items=[]

我收到以下错误:

HTTP/1.1 400 Bad Request
Content-Length: 73
Content-Type: text/plain; charset=UTF-8
Date: Wed, 08 Feb 2017 19:04:37 GMT
Server: akka-http/10.0.3

The request content was malformed:
Expected List as JsArray, but got "[]"

代码是:

import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._
import scala.io.StdIn

case class Item(id: Long, name: String)
case class Order(items: List[Item])

object WebServer {
  implicit val system = ActorSystem()
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher

  implicit val itemFormat = jsonFormat2(Item)
  implicit val orderFormat = jsonFormat1(Order)

  def main(args: Array[String]) {
    val route =
      get {
        pathSingleSlash {
          complete( Item(123, "DefaultItem") )
        }
      } ~
      post {
        path("post_an_order") {
          entity(as[Order]) { order =>
            val itemsCount = order.items.size
            val itemNames = order.items.map(_.name).mkString(", ")
            complete(s"Ordered $itemsCount items: $itemNames")
          }
        }
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

    println("http://localhost:8080/")

    StdIn.readLine()
    bindingFuture.flatMap( _.unbind() ).onComplete( _ => system.terminate() )
  }
}

1 个答案:

答案 0 :(得分:1)

服务器很好。您的HTTPie呼叫有两个问题:

  1. JSON数组需要HTTPie中的:=赋值运算符
  2. 您需要覆盖Accept标头以接收200.否则,HTTPie将假定Accept:application/json并且Akka-HTTP将返回406 - Not Acceptable错误。
  3. http POST http://localhost:8080/post_an_order Accept:text/plain items:=[]