Hi there,
i'm trying to do a POST request with spray but i receive a bad request error.
This is my code:
CASE CLASS:
case class JsonInputStream (fileName: String, stream: String)CLIENT:
import scala.concurrent.Future
import akka.util.Timeout
import spray.httpx.Json4sSupport
import org.json4s.{DefaultFormats, Formats}
import org.json4s.native.Serialization._
import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.IOUtils
object WSClientSpec extends App with Json4sSupport{
import spray.http._
import scala.util.{Success, Failure}
import scala.concurrent.duration._
import akka.actor.ActorSystem
import akka.pattern.ask
import akka.io.IO
import spray.can.Http
import spray.client.pipelining._
import spray.util._
implicit val system = ActorSystem()
import system.dispatcher
implicit def json4sFormats: Formats = DefaultFormats
val fileName = "document.docx"
val path = getClass.getResourceAsStream("/test-documents/" + fileName)
val bytes = IOUtils.toByteArray(path)
val bytes64 = Base64.encodeBase64(bytes)
val streamInString = new String(bytes64)
val json = JsonInputStream(fileName = fileName, stream = streamInString)
val jsonString = write(json)
val pipeline: HttpRequest => Future[HttpResponse] = sendReceive
val response: Future[HttpResponse] = pipeline(Post("http://localhost:8080/jsontest", HttpEntity(MediaTypes.`application/json`, jsonString )))
val a = 0
response onComplete {
case Success(somethingUnexpected) =>
println("---------------------Success--------------------------")
shutdown()
case Failure(error) =>
println("--------------------- ERROR ---------------------")
shutdown()
}
def shutdown(): Unit = {
IO(Http).ask(Http.CloseAll)(1.second).await
system.shutdown()
}SERVER:
import spray.routing.SimpleRoutingApp import spray.httpx.SprayJsonSupport import spray.json.DefaultJsonProtocol import akka.actor.ActorSystem import org.json4s.{DefaultFormats, Formats} object MyJsonSupport extends DefaultJsonProtocol with SprayJsonSupport { implicit val jsonFormats = jsonFormat2(JsonInputStream) } object WSServer extends App with SimpleRoutingApp { import MyJsonSupport._ implicit val system = ActorSystem("my-system") startServer(interface = "localhost", port = 8080) { path("jsontest") { post { entity(as[JsonInputStream]) { j => complete { <h1>TEST 1</h1> } } } } } }the request never stop at breakpoints placed on
<h1> TEST 1 </ h1>. Hangs on breakpoint placed oncase Success.This is the output of somethingUnexpected:
Status: 400 Bad Request - defaultMessage: The request contains bad syntax or cannot be fulfilled. Entity: HttpEntity(text/plain; charset=UTF-8,The request content was malformed: Object is missing required member 'fileName')If you delete the highlighted line the error is gone and the answer is <h1> TEST 1 </ h1>.
The problem is that I need to capture the entity to extract its contents -> fileName and stream
Help me please
Thanks