0

我一直试图让 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的约定

4

2 回答 2

1

这很简单。

该方法withHttpHeaders返回一个 new request,您只是将其丢弃。

尝试像这样更改您的代码:

val request = ws.url("http://myserver.org").withHttpHeaders("charset" -> "utf-8")
于 2017-11-07T20:48:48.853 回答
0

使用version = 2.8.1Play 框架:

必要的进口:

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"))
        )
      }
  }
于 2020-06-14T22:51:26.583 回答