Home > database >  Akka Http route test with formFields causing UnsupportedRequestContentTypeRejection
Akka Http route test with formFields causing UnsupportedRequestContentTypeRejection

Time:12-22

I have a GET request with parameters and a formField.

It works when I use a client like Insomnia/Postman to send the req.

But the route test below fails with the error:

UnsupportedRequestContentTypeRejection(Set(application/x-www-form-urlencoded, multipart/form-data))

(Rejection created by unmarshallers. Signals that the request was rejected because the requests content-type is unsupported.)

I have tried everything I can think of to fix it but it still returns the same error.

It is the formField that causes the problem, for some reason when called by the test it doesnt like the headers.

Is it something to do with withEntity ?

Code:

path("myurl" ) {
  get {
    extractRequest { request =>
      parameters('var1.as[String], 'var2.as[String], 'var3.as[String], 'var4.as[String]) { (var1, var2, var3, var4) =>
        formField('sessionid.as[String]) { (sessionid) =>
          complete {                
              request.headers.foreach(a => println("h="   a))
              }
            }
          }
        }
      }
    }

Test:

// TESTED WITH THIS - Fails with UnsupportedRequestContentTypeRejection(Set(application/x-www-form-urlencoded, multipart/form-data))
class GETTest extends FreeSpec with Matchers with ScalatestRouteTest {
val get = HttpRequest(HttpMethods.GET, uri = "/myurl?var1=456&var2=123&var3=789&var4=987")
.withEntity("sessionid:1234567890")
.withHeaders(
  scala.collection.immutable.Seq(
    RawHeader("Content-Type", "application/x-www-form-urlencoded"),  // same problem if I comment out these 2 Content-Type lines
    RawHeader("Content-Type", "multipart/form-data"),
    RawHeader("Accept", "Application/JSON")
  )
)

get ~> route ~> check {
status should equal(StatusCodes.OK)
}

The exception is thrown before the formField line.

Full exception:

ScalaTestFailureLocation: akka.http.scaladsl.testkit.RouteTest$$anonfun$check$1 at (RouteTest.scala:57)
org.scalatest.exceptions.TestFailedException: Request was rejected with rejection UnsupportedRequestContentTypeRejection(Set(application/x-www-form-urlencoded, multipart/form-data))
    at akka.http.scaladsl.testkit.TestFrameworkInterface$Scalatest$class.failTest(TestFrameworkInterface.scala:24)
}

CodePudding user response:

You could either use:

val get = HttpRequest(HttpMethods.GET, uri = "/myurl?var1=456&var2=123&var3=789&var4=987", entity = FormData("sessionid" -> "1234567.890").toEntity)

or

val get = Get("/myurl?var1=456&var2=123&var3=789&var4=987", FormData("sessionid" -> "1234567.890"))
  • Related