scala - Spray Client I want to return String from Json response -
sorry, new scala. have read futures , akka, still have issue returning string method.
i have method getauthstring should homecoming authentication string(or token). have used spray jsonsupport , can print result
def gettoken(url: string, username: string , password: string) = future[string]{ import myjsonprotocol._ import spray.httpx.sprayjsonsupport._ val pipeline: httprequest => future[authtokenresult[entry]] = (addcredentials(basichttpcredentials(username, password)) ~> sendreceive ~> unmarshal[authtokenresult[entry]] ) val myfutureresponse: future[authtokenresult[entry]] = pipeline(get(url)) myfutureresponse oncomplete { case success(authtokenresult(entry(content(authstring)):: _)) => println(authstring) case failure(error) => println("an error has occured: " + error.getmessage) }
this unmarshal json , print desired authstring. however, printing no me. know oncomplete returns unit. want homecoming authstring can utilize somewhere else request. think have utilize flatmap or map, not sure how. need method homecoming authstring or error.
you don't want homecoming string
, want homecoming future[string]
- 1 time async way create not async block, , that's (usually) waste, making whole async-ness pointless.
i'm not sure why you're wrapping whole thing in future
either - trivial bits of computation can happen on own, there's little value in forcing them onto separate thread. want like:
def gettoken(url: string, ...): future[string] = { ... val myfutureresponse: future[authtokenresult[entry]] = ... myfutureresponse map { case authtokenresult(entry(content(authstring))::_) => authstring } }
so utilize map
transform future
future
computation. "pass through" errors, can utilize recover
or recoverwith
if want handle them in particular way.
then when want utilize future[string]
in spray route, can utilize onsuccess
or oncomplete
directives:
val myroute = (path("/somewhere") & parameter("authdata") { authdata => onsuccess(gettoken(authdata)) { authtoken => complete("authed " + authtoken) } }
this utilize future
in proper async, reactive way, without blocking.
json scala spray-client
No comments:
Post a Comment