setting contentType for Json request in HttpsRequest using Scala

39 Views Asked by At

trying to send httpRequest to remote server but the server seems to be not getting it, curl command like this works fine:

curl -X POST -H "Content-Type: application/json"  -d @payload.json -u "user:password" url

but if we try from a scala program, endpoint does not seem to receive the request. most likely server look for ContentType.application/json in the header! sample code:

val body = "[{\"Field1\":\"XYZ\",\"Field2\":1,\"ID:\"test\"}]"
 
authorization = Some(headers.Authorization(BasicHttpCredentials(username, password)))
val request = HttpRequest(
method = HttpMethods.POST,
uri = url,
headers = authorization.toList,
entity = HttpEntity(
ContentTypes.`application/json`,
s"source=$body&language=Scala&theme==Sunburst"
)
)

val responseFuture: Future[HttpResponse] = Http().singleRequest(request)
responseFuture
.onComplete {
case Success(res) => println(res.toString())
case Failure(_) => sys.error("something wrong" + responseFuture.toString)
}

this returns http code = 200, OK which is fine, but not getting the response as we get it via curl command!

1

There are 1 best solutions below

4
Gaël J On

Hard to definitely answer as the server you're calling doesn't seem to give a helpful error message or HTTP code.

You're sending a body which is not JSON claiming it is.

Change your entity to:

entity = HttpEntity(
  ContentTypes.`application/json`,
  body
)

Not sure, what are source=..&language=... supposed to be? If these are query parameters, add them in the uri (optionally use the Uri class to better describe things).


Note that you could write your body more easily with the """ syntax:

val body = """
[
  {"Field1":"XYZ","Field2":1,"ID:"test"}
]
"""