![](/img/trans.png)
[英]Adding headers to WSRequest in WS client from Play Framework
[英]Play Framework adding headers to http request
我一直在尝试让 WS 向 json api 发出请求。 到目前为止,我无法让 utf-8 正确呈现,记录在这里: Play Framework WS lost unicode chars from external api
我现在正在尝试将字符集添加到请求的 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的约定
这很简单。
withHttpHeaders
方法返回一个新的request
,您只是将其丢弃。
尝试像这样更改您的代码:
val request = ws.url("http://myserver.org").withHttpHeaders("charset" -> "utf-8")
使用version = 2.8.1
的 Play 框架:
必要的进口:
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"))
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.