web services - Scala WS exception error (Web page returned instead of Json) -
i using play scala ws send rest api call web server , exception error. json sent server , response server 1 of following.
- server returns valid json response.
- server returns "no valid json found"
- server returns error web page triggers exception error com.fasterxml.jackson.core.jsonparseexception: unexpected character ('<' (code 60)): expected valid value (number, string, array, object, 'true', 'false' or 'null')
how modify code below contents of web page without exception error?
import play.api.libs.ws._ var temptext = helpers.await(ws.url("localhost:9000/someapi").post(jsontosend)).body println(temptext) tempjson = json.parse(temptext) println(tempjson)
much depends on how "correct" downstream api server is.
in perfect world, assert following facts:
- success case => http
status
200
, httpcontent-type
headerapplication/json
- "no valid json found" => http
status
404
or similar non-200, httpcontent-type
headerapplication/json
- "error web page" => http
status
not200
,content-type
text/html
if above assertions true, can put little bit of "protection" around our response-handling rather jumping in , trying parse json:
val futureoptionalresult = ws.url("localhost").post("...").map { response => response.status match { case 200 => { println(response.body) println(response.json) some(response.json) } case _ => { println(s"not ok: ${response.status} - body is: ${response.body}") none } } }
some notes:
- doing asynchronously easy using
await
, scales better response.json
returns same thing explicitjson.parse
on body- i'm returning
option[jsvalue]
holds returned json if worked
if above assumptions not true, deeper inspection of content-type
header, finer-grained switching on status
value and/or other attributes of response
needed. luck!
Comments
Post a Comment