im writing a function that :
1) send HTTP GET request (response is a valid JSON)
2) parse the response to a json object
code snippet :
val page = url("http://graph.facebook.com/9098498615")
val response = Http(page OK dispatch.as.String)
Await.result(response , 10 seconds)
val myJson= JSON.parseFull(response .toString)
//this isnt helping -> val myJson= JSON.parseRaw(response .toString)
Problem is after this myJson is None while im expecting it to hold the json data from the response.
Help ?
It's not a good idea to use Http(page OK as.String)
because all responses different from HTTP 200 will result in failed Futures. If you need more fine grained control over error handling/reporting, target specific scenarios instead.
import org.jboss.netty.handler.codec.http.{ HttpRequest, HttpResponse, HttpResponseStatus }
def getFacebookGraphData: Either[Exception, String] = {
val page = url("http://graph.facebook.com/9098498615")
val request = Http(page.GET);
val response = Await.result(request, 10 seconds);
(response.getStatusCode: @annotation.switch) match {
case HttpResponseStatus.OK => {
val body = response.getResponseBody() // dispatch adds this method
// if it's not available, then:
val body = new String(response.getContent.array);
Right(body)
}
// If something went wrong, you now have an exception with a message.
case _ => Left(new Exception(new String(response.getContent.array)));
}
}
The default Scala JSON library is not a very good idea either, it's very rough compared to others. Try lift-json
for instance.
import net.liftweb.json.{ JSONParser, MappingException, ParseException };
case class FacebookGraphResponse(name: String, id: String);// etc
implicit val formats = net.liftweb.DefaultFormats;
val graphResponse = JSONParser.parse(body).extract[FacebookGraphResponse];
// or the better thing, you can catch Mapping and ParseExceptions.