喷涂客户端 - 将具有意外内容类型的响应视为application/json?

eug*_*ied 4 scala spray playframework-2.0 spray-json spray-client

当我尝试获取像这样的亚马逊身份数据

val pipeline: HttpRequest => Future[IdentityData] = sendReceive ~> unmarshal[IdentityData]
pipeline(Get("http://169.254.169.254/latest/dynamic/instance-identity/document"))
Run Code Online (Sandbox Code Playgroud)

使用适当的case类和formatter,我收到以下异常

UnsupportedContentType(预期'application/json')

因为亚马逊将其回复标记为文本/纯文本内容类型.他们也不关心Accept header param.是否有一种简单的方法可以告诉spray-json在解组时忽略它?

eug*_*ied 5

在挖掘邮件列表后,我写了一个有效的功能

def mapTextPlainToApplicationJson: HttpResponse => HttpResponse = {
  case r@ HttpResponse(_, entity, _, _) =>
    r.withEntity(entity.flatMap(amazonEntity => HttpEntity(ContentType(MediaTypes.`application/json`), amazonEntity.data)))
  case x => x
}
Run Code Online (Sandbox Code Playgroud)

并在管道中使用它

val pipeline: HttpRequest => Future[IdentityData] = sendReceive ~> mapTextPlainToApplicationJson ~> unmarshal[IdentityData]
pipeline(Get("http://169.254.169.254/latest/dynamic/instance-identity/document"))
Run Code Online (Sandbox Code Playgroud)

很酷的是,只要您的拦截功能具有适当的签名,您就可以拦截和更改任何HttpResponse.