具有内容类型字符集的NodeSeq Marshaller无法解析

时间:2015-01-26 10:36:45

标签: scala character-encoding marshalling spray

尝试获取喷涂终端协商邮递员内容请求。我的XML marshaller似乎让我失望,也就是说,它永远不会根据Accept header和charset解析正确的marshaller选项。

我有以下内容:

object ResponseVO {  
   val NodeSeqMarshaller = Marshaller.delegate[ResponseVO, NodeSeq](ContentType(`text/xml`, `UTF-8`)) { respVO => <ussd><type>{ respVO.respType }</type><message>{ respVO.message }</message></ussd> }

   val supportedContentTypes = List[ContentType](ContentType(`text/xml`, `UTF-8`))
   implicit val marshaller = Marshaller[ResponseVO] { (respVO, ctx) =>
   ctx.tryAccept(supportedContentTypes) match {
    case Some(ContentType(`text/xml`, `UTF-8`)) => NodeSeqMarshaller(respVO, ctx)
    case whatever                               => println(whatever); ctx.rejectMarshalling(supportedContentTypes);
  }
}
}

以及以下路线:

trait USSDRoute { 
  this: SimpleRoutingApp with BootStrappedActorSystem  =>
  val ussdRoute = path("ussd") {
                  parameters('msisdn.as[Long], 'session.as[String], 'type.as[Int], 'msg.as[String], 'network.as[Int]) { (msisdn, session, reqType, msg, network) =>
        complete {
          val reqVO = RequestVO(msisdn, session, reqType, msg, network)
          println(s"received $reqVO")
          ResponseVO(1, "Spirit midget medium escapes from prison, headlines read: Small medium at large!")
        }
      }
    }
  }

不幸的是,我似乎永远不会正确谈判,也就是说,我的marshaller决议会将炸弹炸入“无论”区块并以406回应

"Resource representation is only available with these Content-Types:

文本/ XML;字符集= UTF-8"

我正在使用Postman,我的请求标题为:

GET /ussd?msisdn=0794138690&type=1&network=4&msg=hello&session=99 HTTP/1.1
Host: localhost:9999
Connection: keep-alive
Accept: text/xml; charset=UTF-8
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, 
like Gecko) Chrome/40.0.2214.91 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,nl;q=0.6

这可能是小而愚蠢的事情 - 希望有人可以帮助引导我朝着正确的方向前进。

谢谢

1 个答案:

答案 0 :(得分:1)

查看案例类ContentType的定义方式:

case class ContentType(mediaType: MediaType, definedCharset: Option[HttpCharset])

请注意,definedCharset被定义为Option[HttpCharset],因此您的模式通过

匹配
case Some(ContentType(`text/xml`, `UTF-8`)) => ...

永远不会成功。因此,您需要使用Some成功执行模式匹配:

case Some(ContentType(`text/xml`, Some(`UTF-8`))) => ...