我一直在努力让WS向json api发出请求。到目前为止,我无法正确呈现utf-8,在此处记录:Play Framework WS losing unicode chars from external api
我现在正在尝试将charset添加到请求的http标头中。但是,我似乎无法做到这一点。如果我运行以下内容:
val request = ws.url("http://myserver.org")
request.withHttpHeaders("charset" -> "utf-8")
println("request headers: " request.headers)
request.get().map { response =>
println("response headers: " + response.headers)
...
这将生成以下内容:
request headers: Map()
response headers: Map(Date -> Buffer(Tue, 07 Nov 2017 20:11:58 GMT), Server -> Buffer(Jetty(8.1.5.v20120716)), Content-Type -> Buffer(application/json), Cache-Control -> Buffer(private, must-revalidate, max-age=0), Content-Length -> Buffer(9822), X-Content-Type-Options -> Buffer(nosniff))
任何人都可以诊断出我做错了什么吗?为什么请求标题映射为空?我遵循了2.6 scala doc
的约定答案 0 :(得分:1)
这很简单。
方法withHttpHeaders
会返回您刚刚丢弃的新request
。
尝试更改您的代码:
val request = ws.url("http://myserver.org").withHttpHeaders("charset" -> "utf-8")
答案 1 :(得分:0)
使用Play框架的version = 2.8.1
:
必要进口:
import play.api._
import play.api.mvc._
import play.api.http.HttpEntity
带有请求标头的示例方法:
def index() = Action { implicit request: Request[AnyContent] => {
val (status, message) = report.renderReportsJson
// Adding headers for dev testing
if (status) {
Result(
header = ResponseHeader(200, Map("Access-Control-Allow-Origin" -> "*")),
body = HttpEntity.Strict(ByteString(message), Some("text/plain"))
)
}
else
{
Result(
header = ResponseHeader(501, Map("Access-Control-Allow-Origin" -> "*")),
body = HttpEntity.Strict(ByteString(message), Some("text/plain"))
)
}
}