awfulHack
awfulHack

Reputation: 875

Play Framework adding headers to http request

I've been trying to get WS to make a request to a json api. So far I am not able to get utf-8 to render correctly, documented here: Play Framework WS losing unicode chars from external api

I'm now trying to add charset to the http headers of the request. But, I don't seem to be able to do this. If I run the following:

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)
...

This will generate the following:

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))

Can anyone diagnose what I'm doing wrong? why is the request header map empty? I've followed the conventions for according the 2.6 scala doc

Upvotes: 0

Views: 2674

Answers (2)

ForeverLearner
ForeverLearner

Reputation: 2113

With version = 2.8.1 of Play Framework:

Necessary imports:

import play.api._
import play.api.mvc._
import play.api.http.HttpEntity

Sample method with request headers:

  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"))
        )
      }
  }

Upvotes: 0

mfirry
mfirry

Reputation: 3692

It's quite simple.

The method withHttpHeaders returns a new request, that you're just discarding.

Try change your code like this:

val request = ws.url("http://myserver.org").withHttpHeaders("charset" -> "utf-8")

Upvotes: 1

Related Questions