如何在Akka HTTP中将`text/plain`解组为JSON

Dav*_*est 5 parsing json http spray-json akka-http

我正在使用遗留的HTTP API(我无法更改),它在正文中以JSON响应,但是给出了一个Content-Type: text/plain; charset=utf-8标题.

我试图将HTTP主体解组为JSON,但我得到以下异常: akka.http.scaladsl.unmarshalling.Unmarshaller$UnsupportedContentTypeException: Unsupported Content-Type, supported: application/json

我的代码看起来像这样:

import spray.json.DefaultJsonProtocol
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import akka.http.scaladsl.unmarshalling._

case class ResponseBody(status: String, error_msg: String)

object ResponseBodyJsonProtocol extends DefaultJsonProtocol {
  implicit val responseBodyFormat = jsonFormat2(ResponseBody)
}

def parse(entity: HttpEntity): Future[ResponseBody] = {
  implicit val materializer: Materializer = ActorMaterializer()
  import ResponseBodyJsonProtocol._
  Unmarshal[HttpEntity](entity).to[ResponseBody]
}
Run Code Online (Sandbox Code Playgroud)

HTTP响应示例如下所示:

HTTP/1.1 200 OK
Cache-Control: private
Content-Encoding: gzip
Content-Length: 161
Content-Type: text/plain; charset=utf-8
Date: Wed, 16 Dec 2015 18:15:14 GMT
Server: Microsoft-IIS/7.5
Vary: Accept-Encoding
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET

{"status":"1","error_msg":"Missing parameter"}
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能忽略Content-TypeHTTP响应并解析为JSON?

Dav*_*est 7

我找到的一个解决方法是在解组之前手动设置Content-Typeon HttpEntity:

def parse(entity: HttpEntity): Future[ResponseBody] = {
  implicit val materializer: Materializer = ActorMaterializer()
  import ResponseBodyJsonProtocol._
  Unmarshal[HttpEntity](entity.withContentType(ContentTypes.`application/json`)).to[ResponseBody]
}
Run Code Online (Sandbox Code Playgroud)

似乎工作正常,但我对其他想法持开放态度......